如何将数组中的对象,根据某个key值进行合并

新手上路,请多包涵

cc32a0b5acb3dfaf5be595dc81f84e0.png
上图为源数据

想得到如图所示的结果(想根据 time 这个属性合并数据)
c9eb472dc12109b3c3bd4d98553633a.png

阅读 3.7k
4 个回答

此类key相同的合并问题都可以使用hash法来处理,定义一个对象以检测key是否存在,利用数组里对象的指向引用,将hash对象改变影响数组里面的对象,一次循环即可

let arr = [{
      time: 0.1,
      h1: '11'
    }, {
      time: 0.5,
      h1: '22'
    }, {
      time: 1.5,
      h1: '33'
    }, {
      time: 0.1,
      h2: '330'
    }]

    let hash = {}

    const newArr = arr.filter(s => {
      if (hash[s.time]) {
        hash[s.time] = Object.assign(hash[s.time], s)
        return false
      } else {
        hash[s.time] = s
        return true
      }
    })
var arr = [
    {time:"a", a:1},
    {time:"a", b:2},
    {time:"b", a:1},
    {time:"b", b:6},
    {time:"c", a:10},
];

arr.reduce((p,c)=>{
    if(p.find(item=>item.time === c.time)){
        Object.assign(p.find(item=>item.time === c.time),c)
    }else{
        p.push(c)
    }
    return p
},[])
let list = [
  { time: 0.1, h1: 322 },
  { time: 0.1, h2: 122 },
  { time: 0.3, h1: 22 },
  { time: 0.1, h4: 562 },
  { time: 2.1, h1: 22 },
  { time: 3.1, h1: 32 },
  { time: 2.1, h1: 321 },
];
let newList = list.reduce((a, c) => {
  let index = a.findIndex((e) => e.time == c.time);
  if (index != -1) {
    a[index] = { ...a[index], ...c };
  } else {
    a.push(c);
  }
  return a;
}, []);
console.log("newList: ", newList);

image.png

代码

var list = [{time:1.5,h1:'33'},{time:1.5,h2:'833'},{time:0.1,h1:'11'}]
Object.values(list.reduce((acc,cur)=>(Object.assign((acc[cur.time]||={}),cur),acc),[]))

结果

0: {time: 1.5, h1: "33", h2: "833"}
1: {time: 0.1, h1: "11"}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题