简体   繁体   English

按 ID javascript 合并数组中的对象

[英]Merge objects in array by ID javascript

So I am trying to merge 2 arrays of objects by ID-s ( ID and AUTOMOBIL ) with this code I only push last array of objects(OPREMA) .因此,我试图通过 ID-s( IDAUTOMOBIL )合并 2 个 arrays 对象与此代码我只推送最后一个array of objects(OPREMA) Someone have any idea how can I get all of them in the spot they should be?有人知道我怎样才能把他们都放在他们应该在的地方?

So when ID in a1 is == 1 I need all of OPREMA in a2 witch AUTOMOBIL is equal to 1 to save it together it a1 , but with this code it's only saving last one.因此,当a1中的ID== 1时,我需要a2中的所有OPREMA女巫AUTOMOBIL等于1以将其保存在一起a1 ,但使用此代码它只保存最后一个。

 const a1 = [ { ID: "2", TIP: "A3", VRSTA: "Limousine", $$hashKey: "object:3" }, { ID: "1", TIP: "A5", VRSTA: "Coupe", $$hashKey: "object:7" }, ]; const a2 = [ { AUTOMOBIL: "1", OPREMA: { ID: "5", NAZIV_OPREME: "Automatski", VRSTA_OPREME: "2", CIJENA: "15000", OPIS: "Automatski mjenjač", }, }, { AUTOMOBIL: "1", OPREMA: { ID: "3", NAZIV_OPREME: "Benzin", VRSTA_OPREME: "1", CIJENA: "7000", OPIS: "Gorivo benzin", }, }, { AUTOMOBIL: "1", OPREMA: { ID: "19", NAZIV_OPREME: "1.0", VRSTA_OPREME: "5", CIJENA: "7000", OPIS: "potrosnja 3-6l", }, }, { AUTOMOBIL: "1", OPREMA: { ID: "11", NAZIV_OPREME: "Sportback", VRSTA_OPREME: "3", CIJENA: "70000", OPIS: "sportski izgled šasije", }, }, { AUTOMOBIL: "1", OPREMA: { ID: "8", NAZIV_OPREME: "Quattro", VRSTA_OPREME: "4", CIJENA: "15000", OPIS: "Pogon na sve kotače", }, }, ]; const a3 = a1.map(t1 => ({...t1, ...a2.find(t2 => t2.AUTOMOBIL === t1.ID) })); //RESULT OF a3 console.log(a3);

In your question you never specified how exactly you want the elements of a2 to be saved in the a1 element.在您的问题中,您从未指定要将 a2 的元素保存在 a1 元素中的确切方式。 I'm assuming that you need them as a array under the OPREMA property.我假设您需要将它们作为 OPREMA 属性下的数组。 Your code was pretty close but instead of find you needed to use filter to keep all elements that match.您的代码非常接近,但您需要使用过滤器而不是 find 来保持所有匹配的元素。

const a3 = a1.map(t1 => {
      const matchingElements = a2.filter(t2 => t2.AUTOMOBIL === t1.ID);
      return ({...t1, OPREMA: matchingElements.map(({ OPREMA }) => OPREMA) });
});

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

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