VueJs-将对象从数组检索到新的对象数组

时间:2019-03-05 16:47:27

标签: javascript arrays vue.js

任何人都可以帮助我找到一种方法,将对象从对象数组中返回,以将所有对象合并为具有对象名而不是键的新对象数组。

array = [
  1: {
    cart: { fruits: {}, vegetables: {}, juices: {}}
  },
  2: {
    cart: { boxes: {}, tools: {}, bottles: {}}
  }
]

我正在尝试使用方法和计算属性在 Vuejs 中获得此特定输出,但是我只能使用键作为常规数组来获得输出。我需要对象名称而不是键。

预期产量

newArray = {
  cart: { fruits: {}, vegetables: {}, juices: {} boxes: {}, tools: {}, bottles: {}}
}

2 个答案:

答案 0 :(得分:1)

您可以使用reducedestructuring assignment并使用键以所需的格式合并对象。

let array = [{cart: { fruits: {}, vegetables: {}, juices: {}}},{cart: { boxes: {}, tools: {}, bottles: {}}}]

let op = array.reduce( (op,inp) => {
  let key = Object.keys(inp)[0]
  op[key] = {...op[key], ...inp[key]}
  return op
},{})

console.log(op)

答案 1 :(得分:0)

一种可能的解决方案是使用Array.reduce(),并在数组中每个对象的Object.keys()上进行迭代时,使用Object.assign()将它们收集到最终预期输出的相关键上: / p>

let arr = [
  {
    cart: {fruits: {}, vegetables: {}, juices: {}},
    other: {foo: {}, bar: {}}
  },
  {
    cart: {boxes: {}, tools: {}, bottles: {}},
    other: {oof: {}, rab: {}}
  }
];

let res = arr.reduce((acc, obj) =>
{
    Object.keys(obj).forEach(key =>
    {
        acc[key] = acc[key] || {};
        Object.assign(acc[key], obj[key]);
    });

    return acc;
}, {});

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}