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

时间:2019-07-19 13:21:13

标签: javascript json ajax reactjs

将数组重组为输出的最佳方法是什么?我需要将所有值键(无论是否为数组)合并到共享相同名称键的对象中。我当前的数组是:

uint64_t

我想基于数组集合构造一个新数组:

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"}
]

2 个答案:

答案 0 :(得分:0)

假设有一个嵌套对象数组,则可以迭代该数组,使用所需键查找对象,然后将最内部的对象应用于给定对象。

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

答案 1 :(得分:0)

只需要遍历并合并。

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)