简体   繁体   English

使用循环合并具有相同键的数组中的javascript数组

[英]Merge javascript array in array with same key using loop

What is the best way to reorganize an array into output?将数组重组为输出的最佳方法是什么? I need to merge all value keys (whether array or not) into objects sharing the same name key.我需要将所有值键(无论是否为数组)合并到共享相同名称键的对象中。 My current array is:我目前的数组是:

brands: [
  0:ZARA: {product: "ZARA Black Shiny Shirt"}
  1:ZARA: {fit: "Slim Fit"}
  2:ZARA: {size: "46"}
  3:H&M: {product: "H&M Black Shirt"}
  4:H&M: {fit: "Regular Fit"}
  5:H&M: {size: "44"}
]

I want to construct a new array based on sets of arrays:我想基于数组集构造一个新数组:

brands: [
  0:ZARA: {product: "ZARA Black Shiny Shirt",fit: "Slim Fit",size: "46"},
  1:H&M: {product: "H&M Black Shirt",fit:50 "Regular Fit",size: "44"}
]

Just need to loop over it and combine.只需要遍历它并组合。

 var brands = [ {ZARA: {product: "ZARA Black Shiny Shirt"}}, {ZARA: {fit: "Slim Fit"}}, {ZARA: {size: "46"}}, {'H&M': {product: "H&M Black Shirt"}}, {'H&M': {fit: "Regular Fit"}}, {'H&M': {size: "44"}} ] /* First step loop over the items and look to combine the same ones */ var combined = brands.reduce((obj, entry) => { // split it up into its part, the item and the detail of it const [key, detail] = Object.entries(entry)[0] // if we have not seen this item yet, set it if (!obj[key]) obj[key] = {} // Add the new item details to the item obj[key] = {...obj[key], ...detail} // return the updated object to the reduce method return obj }, {}) // show the object we built with the combined details console.log(combined) // now you want it to be an array of objects so need to loop to make that var finalOutput = Object.entries(combined) .reduce((out, [key, obj]) => { out.push({[key]: obj}) return out }, []) console.log(finalOutput)

Assuming an array of nested object, then you could iterate the array, find the object with the wanted key and apply the most inner object to the given obejct.假设一个嵌套对象数组,那么您可以迭代该数组,找到具有所需键的对象并将最内部的对象应用于给定的对象。

 var brands = [{ ZARA: { product: "ZARA Black Shiny Shirt" } }, { ZARA: { fit: "Slim Fit" } }, { ZARA: { size: "46" } }, { 'H&M': { product: "H&M Black Shirt" } }, { 'H&M': { fit: "Regular Fit" } }, { 'H&M': { size: "44" } }], result = brands.reduce((r, o) => { Object.entries(o).forEach(([k, v]) => { var temp = r.find(q => k in q); if (!temp) r.push(temp = { [k]: {} }); Object.assign(temp[k], v); }); return r; }, []); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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

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