gpt4 book ai didi

javascript - 将对象数组转换为具有某些值对的单个对象

转载 作者:行者123 更新时间:2023-11-28 11:11:34 25 4
gpt4 key购买 nike

我知道关于如何将数组转换为对象有很多问题我知道你可以做这样的事情.. object = {...arr}; 但我的问题更具体

假设我有一个像这样的对象数组..

[
{
dataType: something,
dataValue: book
},
{
dataType: food,
dataValue: brocolli
},
{
dataType: object,
dataValue: chair
},
]

我想创建一个看起来像这样的对象..

{
something: book,
food: brocolli,
object: chair
}

我尝试做这样的事情......

arr.forEach(item => {
newarray.push({arr.dataType: arr.dataValue});
})
newObject = {...newarray}

但这不起作用..任何帮助将不胜感激!

最佳答案

您可以使用减少

var arr = [{
dataType: 'something',
dataValue: 'book'
},
{
dataType: 'food',
dataValue: 'brocolli'
},
{
dataType: 'object',
dataValue: 'chair'
},
]

var obj = arr.reduce((c, {dataType,dataValue}) => Object.assign(c, {[dataType]: dataValue}), {});

console.log(obj);

关于javascript - 将对象数组转换为具有某些值对的单个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49419683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com