json 用相同的键合并对象javascript

osh3o9ms  于 2023-04-22  发布在  Java
关注(0)|答案(2)|浏览(108)

我想把有相同键的对象合并成一个对象。例如下面的第一个数组就是我现在的数组。我想把它转换成第二个数组
转换如下

[
  {
    "speed": 779.5,
    "id": 1
  },
  {
    "code": "04.x.D3",
    "id": 1
  },
  {
    "temperature": 49,
    "id": 1
  },
  {
    "range": 0,
    "id": 1
  },
  {
    "temperature": 41,
    "id": 2
  },
  {
    "range": 3,
    "id": 2
  }
]

进入这个

[
  {
    "speed": 779.5,
    "code": "04.x.D3",
    "temperature": 49,
    "range": 0,
    "id": 1
  },
  {
    "temperature": 41,
    "range": 3,
    "id": 2
  }
]
roejwanj

roejwanj1#

const start = [
  {
    "speed": 779.5,
    "id": 1
  },
  {
    "code": "04.x.D3",
    "id": 1
  },
  {
    "temperature": 49,
    "id": 1
  },
  {
    "range": 0,
    "id": 1
  },
  {
    "temperature": 41,
    "id": 2
  },
  {
    "range": 3,
    "id": 2
  }
];

const result = start.reduce(
  (accumulator, value) => {
    // Check if there is already an object in the array with the same id.
    const existing = accumulator.findIndex(({ id }) => value.id === id);
    // If there is an existing object:
    if (existing > -1) {
      // Shallow merge the properties together.
      accumulator[existing] = { ...accumulator[existing], ...value };
      return accumulator;
    }
  
    // Else append this object to the array.
    return accumulator.concat(value);
  },
  // Start with an empty array.
  []
);

console.log(result);
dtcbnfnu

dtcbnfnu2#

const data = [ { "speed": 779.5, "id": 1 }, { "code": "04.x.D3", "id": 1 }, { "temperature": 49, "id": 1 }, { "range": 0, "id": 1 }, { "temperature": 41, "id": 2 }, { "range": 3, "id": 2 } ];

const result = data.reduce((prev, current) => {
  const index = prev.findIndex(o => o.id === current.id);
  return index < 0 ?
    prev.push(current) && prev :
    prev.splice(index, 1, {...prev[index], ...current}) && prev;
}, []);

console.log(result);

相关问题