首页 > javascript > VueJs - 将数组中的对象检索到新的对象数组中

VueJs - 将数组中的对象检索到新的对象数组中 (VueJs - Retrieve objects from array into new object array)

问题

任何人都可以帮我找到一种方法从对象数组返回对象,将所有对象连接到一个新的对象数组,而不是键。

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

我试图使用方法和计算属性在Vuejs中获取此特定输出,但我只能使用键作为普通数组获得输出。我需要对象名而不是键。

预期产出

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

解决方法

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

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


问题

Can anyone please help me find a way to return objects from an object array to concat all of them into a new object array with object names instead of keys.

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

I am trying to get this specific output in Vuejs using methods and computed properties, But I am only able to get the output with keys as a normal array. I need the object name instead of keys.

Expected output

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

解决方法

One possible solution is to use Array.reduce() and while iterating over the Object.keys() of every object in the array use Object.assign() to collect they on the related key of the final expected output:

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

相似信息