关于数组对象筛选问题 javascript

http404
  • 242

数据中有多个相同的name值,我想把相同的name对应的code放在一个数组里面,请问用什么方法实现好些

let arr = [{name:'测试一',code:'20001'},{name:'测试三',code:'20002'},{name:'测试六',code:'20003'},{name:'测试一',code:'20004'},{name:'测试三',code:'20005'},...]

//最后想得到下面结果
[{name:'测试一',fund:[{code:'20001'},{code:'20004'}]},{name:'测试三',fund:[{code:'20002'},{code:'20005'}]},{name:'测试六',fund:[{code:'20003'}]},...]
评论
阅读 588
3 个回答
let arr = [
  { name: '测试一', code: '20001' },
  { name: '测试三', code: '20002' },
  { name: '测试六', code: '20003' },
  { name: '测试一', code: '20004' },
  { name: '测试三', code: '20005' },
  { name: '测试四', code: '20006' },
  { name: '测试六', code: '20007' },
  { name: '测试一', code: '20008' },
  { name: '测试三', code: '20009' },
]
var brr = {}
arr.forEach((item, index) => {
  if (brr[item.name]) {
    if (Array.isArray(brr[item.name].fund)) {
      var fund = [...brr[item.name].fund, item.code]
    } else {
      var fund = [brr[item.name].code, item.code]
    }
    brr[item.name] = { name: item.name, fund }

  } else {
    brr[item.name] = { name: item.name, code: item.code }
  }
  })
  var crr = Object.values(brr)
  let result = []
  crr.forEach((item, index) => { 
    if (item.fund) {
      let darr = []
      item.fund.forEach((itemF, indexF) => { 
        darr.push({code:itemF})
      })
      item.fund = darr
    } else { 
      item.fund = [{ code: item.code }]
      delete item.code
    }
    result.push(item)
  })

  console.log(result);

本质上就是数组元素分组,可以参考一下 groupBy

let arr = [

    {name:'测试一',code:'20001'},
    {name:'测试三',code:'20002'},
    {name:'测试六',code:'20003'},
    {name:'测试一',code:'20004'},
    {name:'测试三',code:'20005'},
    {name:'测试四',code:'20006'},
    {name:'测试六',code:'20007'},
    {name:'测试一',code:'20008'},
    {name:'测试三',code:'20009'},
    ]
var brr = {}
arr.forEach((item,index)=>{
    if(brr[item.name]){
        if(Array.isArray(brr[item.name].fund)){
            var fund = [...brr[item.name].fund,item.code]
        }else{
            var fund = [brr[item.name].code,item.code]
        }
        brr[item.name] = {name:item.name,fund}
        
    }else{
        brr[item.name] = {name:item.name,code:item.code}
    }
})

console.log(Object.values(brr))
宣传栏