简体   繁体   English

在 json 数组 javascript 中组合相同的对象

[英]Combining same objects in json array javascript

I have this array:我有这个数组:

[{ "id": 1, "myId": "100", "name": "amey" }, { "id": 2, "myId": "100", "name": "anuj" }, { "id": 3, "myId": "101", "name": "suraj" }, { "id": 4, "myId": "101", "name": "suraj h" }]

I want output like this:我想要这样的 output :

[{ "id": 1, "myId": "100", "name": ["amey", "anuj"] }, { "id": 3, "myId": "101", "name": ["suraj", "suraj h] }]

How can I do this using javascript如何使用 javascript 做到这一点

for (var i = 0; i < myarray.length; i++) {
  //And loop again for duplicate data
  for (var j = i + 1; j < myarray.length; j++) {
    if (
      myarray[i].VENDOR_ID == myarray[j].VENDOR_ID &&
      myarray[i].ORDER_ID === myarray[j].ORDER_ID
    ) {
      var tmp = myarray[j].NAME;
      console.log(tmp);
      myarray[j].NAME = [];
      myarray[j].NAME.push(tmp);
      myarray[j].NAME.push(myarray[i].NAME);
      myarray[i] = {};
    }
  }
}

You can use Array.prototype.reduce() :您可以使用Array.prototype.reduce()

 const arr1 = [{ "id": 1, "myId": "100", "name": "amey" }, { "id": 2, "myId": "100", "name": "anuj" }, { "id": 3, "myId": "101", "name": "suraj" }, { "id": 4, "myId": "101", "name": "suraj h" }] const reduced = arr1.reduce((acc, item) => { // 1. check if the 'acc' array already contains an item with the same 'myId' attribute const itemIndex = acc.findIndex(it => it.myId === item.myId); // 2. if there isn't any, push into the 'acc' array a copy of the item, // with the 'name' property converted into an array of strings // otherwise simply push the 'name' into the already existing item if (itemIndex === -1) { acc.push({...item, name: [item.name] }); } else { acc[itemIndex].name.push(item.name) } return acc; }, []); // test console.log(reduced);

You can use an array reduce into an object and return the array of values.您可以将数组归约到 object 并返回值数组。 Reduce into an object using the myId property as the key to group by.使用myId属性作为分组依据,减少为 object。 Shallow copy any existing state and and name array, appending the new name value from the current element.浅复制任何现有的 state 和name数组,并从当前元素附加新name值。

Object.values(
  input.reduce(
    (acc, { id, myId, name }) => ({
      ...acc,
      [myId]: {
        ...(acc[myId] || { id, myId }),
        name: [...(acc[myId]?.name || []), name]
      }
    }),
    {}
  )

 const input = [ { id: 1, myId: "100", name: "amey" }, { id: 2, myId: "100", name: "anuj" }, { id: 3, myId: "101", name: "suraj" }, { id: 4, myId: "101", name: "suraj h" } ]; const res = Object.values( input.reduce( (acc, { id, myId, name }) => ({...acc, [myId]: {...(acc[myId] || { id, myId }), name: [...(acc[myId]?.name || []), name] } }), {} ) ); console.log(JSON.stringify(res));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM