【问题标题】:foreach array with one key [duplicate]一键foreach数组[重复]
【发布时间】:2021-06-04 20:10:50
【问题描述】:

我有一个具有不同值的对象。
let arr = [{"Personal": "1000"},{"sport": "2100"},{"Industrial": "1200"},{"Commercial": "2300"},
{"Fashion": "1300"},{"Documentary": "2600"}]

我怎样才能找到它们,然后将它们放在一个对象中并为它们取一个名字,如下所示:

"photo_type": {
    "Personal": "1000",
    "sport": "2100",
    "Industrial": "1200",
    "Commercial": "2300",
    "Fashion": "1300",
    "Documentary": "2600"
}

我不希望它们像 0 和 1 和 2 一样。

【问题讨论】:

标签: javascript arrays object foreach


【解决方案1】:

你可以试试这个

const arr = [{"Personal": "1000"},{"sport": "2100"},{"Industrial": "1200"},{"Commercial": "2300"},{"Fashion": "1300"},{"Documentary": "2600"}]
let result = {}
arr.forEach(member => {result = {...result, ...member}}

【讨论】:

    【解决方案2】:

    您可以使用Object.assign 并通过扩展数组来创建一个对象。

    let array = [{ Personal: "1000" }, { sport: "2100" }, { Industrial: "1200" }, { Commercial: "2300" }, { Fashion: "1300" }, { Documentary: "2600" }],
        object = Object.assign({}, ...array);
    
    console.log(object);

    【讨论】:

    • Doh!比我的多步骤操作好多了。
    猜你喜欢
    • 2013-12-27
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2012-06-15
    相关资源
    最近更新 更多