如何用js从数组中把各项值组成一个特定的词?

作者站长头像
站长
· 阅读数 19
var list = [
    {
        "name": "花",
        "index": 10,
        "len": 4,
        "left": 150,
        "bottom": 108
    },
    {
        "name": "花",
        "index": 0,
        "len": 4,
        "left": 150,
        "bottom": 0
    },
    {
        "name": "花",
        "index": 8,
        "len": 4,
        "left": 950,
        "bottom": 0
    },
    {
        "name": "草",
        "index": 14,
        "len": 4,
        "left": 550,
        "bottom": 108
    },
    {
        "name": "草",
        "index": 15,
        "len": 4,
        "left": 650,
        "bottom": 108
    },
    {
        "name": "草",
        "index": 15,
        "len": 4,
        "left": 650,
        "bottom": 108
    }
];

var aa = '花花草草';

vue中需要写一个通用的方法,当aa这个词跟list中各项的name值相等时,name置空,最后得到的list是

list = [
    {
        "name": "花",
        "index": 10,
        "len": 4,
        "left": 150,
        "bottom": 108
    },
    {
        "name": "",
        "index": 0,
        "len": 4,
        "left": 150,
        "bottom": 0
    },
    {
        "name": "",
        "index": 8,
        "len": 4,
        "left": 950,
        "bottom": 0
    },
    {
        "name": "",
        "index": 14,
        "len": 4,
        "left": 550,
        "bottom": 108
    },
    {
        "name": "",
        "index": 15,
        "len": 4,
        "left": 650,
        "bottom": 108
    },
    {
        "name": "草",
        "index": 15,
        "len": 4,
        "left": 650,
        "bottom": 108
    }
];

就是把list中的name值连接起来跟aa值相等时置空的方法

回复
1个回答
avatar
test
2024-06-19
let start = list.map(i => i.name).join('').indexOf(aa)
if(start > -1){
    let end = Math.min(start + aa.length, list.length)
    for (let index = start; index < end; index++) {
        list[index].name = ''
    }
}
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容