Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

js for循环过滤改造对象

原始对象↓

let obj1 = [{name:'蔬菜-1',id:'123'},
            {name:'蔬菜-2',id:'122'},
            {name:'新鲜蔬菜',id:'112'},
            {name:'劣质苹果',id:'114'},
            {name:'苹果-新增',id:'115'},
            {name:'苹果-优质',id:'116'},
            {name:'香蕉',id:'106'},
            {name:'梨子',id:'156'}]

期待的效果↓

let result = [{name:'蔬菜',id:'123'},
              {name:'苹果',id:'114'},
              {name:'香蕉',id:'106'},
              {name:'梨子',id:'156'}]

也就是如果name里面有相同的字符,改造后的name就是那个相同的字符,其余的去掉,然后id的话就用在前的第一个就行,没有相同的话就一起遍历到result里面,这该怎么写呢

不知道我的问题描述是否清晰,还请各位大神指教,小弟感激不尽!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

这个简单,遍历一遍用map存起来,最后转数组就行,给你写个伪代码

const result = new Map()
obj1.forEach(item => {
  const name = item.name.split('-')[0]
  if (!result.has(name)) {
    result.set(name, { name, id: item.id })
  }
})
return [result.values()]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...