Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

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:

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

How can I do this using 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] = {};
    }
  }
}
question from:https://stackoverflow.com/questions/65841673/combining-same-objects-in-json-array-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use an array reduce into an object and return the array of values. Reduce into an object using the myId property as the key to group by. Shallow copy any existing state and and name array, appending the new name value from the current element.

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...