【问题标题】:Combine an array into 1 [duplicate]将一个数组合并为 1 [重复]
【发布时间】:2023-03-14 05:20:01
【问题描述】:

这是我的数组:

array = [{plant: "shrub", length: "2 meters"},
    {animal: "dog", age: "5 years old"}]

我想要的结果是:

desiredArray = {plant: "shrub", length: "2 meters", animal: "dog", age: "5 years old" }

帮我组合多个长度的数组。

【问题讨论】:

  • Object.assing({}, ...array)

标签: javascript arrays


【解决方案1】:

您可以使用reduce

const array = [
    { plant: 'shrub', length: '2 meters' },
    { animal: 'dog', age: '5 years old' },
];

const result = array.reduce((acc, val) => ({ ...acc, ...val }), {});

console.log(result);

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 1970-01-01
    • 2017-01-01
    • 2017-03-20
    • 2019-08-13
    • 2014-06-29
    • 2022-01-22
    • 1970-01-01
    • 2015-02-02
    相关资源
    最近更新 更多