js 将数组里相同name合并并将value值放到一个数组里 有什么高效便捷的方法?

仙女哥哥
  • 31

原始数据

let arr = [
  {
    name: "主场馆",
    value: "摄像头一",
    unit:'a',
    type:'类型一'
  },
  {
    name: "主场馆",
    value: "摄像头二",
    unit:'b',
    type:'类型二'
  },
  {
    name: "主场馆",
    value: "摄像头三",
    unit:'c',
    type:'类型三'
  },
  {
    name: "体育馆",
    value: "摄像头一",
    unit:'a',
    type:'类型一'
  },
  {
    name: "体育馆",
    value: "摄像头二",
    unit:'a',
    type:'类型二'
  }
];

合并之后

let newArr = [
  {
    name: "主场馆",
    values: [{
        cameraName:"摄像头一",
        unit:'a',
        type:'类型一'
    },
    {
        cameraName:"摄像头二",
        unit:'b',
        type:'类型二'
    },{
        cameraName:"摄像头三",
        unit:'c',
        type:'类型三'
    }],
  },
  {
    name: "体育馆",
    values: [{
        cameraName:"摄像头一",
        unit:'a',
        type:'类型一'
    },
    {
        cameraName:"摄像头二",
        unit:'b',
        type:'类型二'
    },{
        cameraName:"摄像头三",
        unit:'c',
        type:'类型三'
    }],
  },
];
回复
阅读 1.5k
3 个回答
✓ 已被采纳
let arr = [
  {
    name: "主场馆",
    value: "摄像头一"
  },
  {
    name: "主场馆",
    value: "摄像头二"
  },
  {
    name: "主场馆",
    value: "摄像头三"
  },
  {
    name: "体育馆",
    value: "摄像头一"
  },
  {
    name: "体育馆",
    value: "摄像头二"
  },
  {
    name: "体育馆",
    value: "摄像头三"
  }
];
Object.entries(
  arr.reduce(
    (prev, next) => ({
      ...prev,
      [next.name]: [...(prev[next.name] || []), next.value]
    }),
    {}
  )
).map(([name, value]) => ({ name, value }));

更改后

Object.entries(
  arr.reduce(
    (prev, next) => ({
      ...prev,
      [next.name]: [...(prev[next.name] || []), { ...next }]
    }),
    {}
  )
).map(([name, value]) => ({ name, value }));

看我的:

var result = [...new Set(arr.map(row=> row.name))].map(key=> ({
    name: key, values: arr.filter(row=> row.name==key).map(row=> row.value)
}))
console.log(result)

更多字段:

var result = [...new Set(arr.map(row=> row.name))].map(key=> ({
    ...arr.filter(row=> row.name==key)[0],
    values: arr.filter(row=> row.name==key).map(row=> row.value)
}))
console.log(result)
let obj = {};
let newArr = [];
arr.forEach(item => {
    if (obj[item.name]) {
        obj[item.name].push(item.value);
    } else {
        obj[item.name] = [item.value];
     }
})
Object.keys(obj).forEach(key => {
   newArr.push({
       name: key,
       value: obj[key]
   })
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏