gpt4 book ai didi

javascript - 如何遍历对象数组并制作键值对?

转载 作者:行者123 更新时间:2023-12-03 07:24:46 25 4
gpt4 key购买 nike

我有一个这样的对象数组:

let someObj = {
items: [{
id: '12',
value: true
}, {
id: '34',
value: true
}, {
id: '56',
value: false
}]

}

我想将它添加到一个现有对象中,其中 id 是该对象的键,如下所示:

let obj = {
someKey: someValue,
'12': true,
'34': true,
'56': false,
}

最佳答案

您可以使用 Array#reduce 实现您的目标,如下所示:

const input = {
items: [{
id: '12',
value: true
}, {
id: '34',
value: true
}, {
id: '56',
value: false
}]
}

const output = input.items.reduce((o, {
id,
value
}) => (o[id] = value, o), {})

console.log(output)

此外,也许最简单的方法可能是使用 Array#map 将对象转换为,然后使用 Object.fromPairs< 将它们转换为对象:

const input = {
items: [{
id: '12',
value: true
}, {
id: '34',
value: true
}, {
id: '56',
value: false
}]
}

const output = Object.fromEntries(input.items.map(({
id,
value
}) => [id, value]))

console.log(output)

最后,这是一个函数式方法:

  // Composes two functions
const compose = f => g => x => f (g (x))

// Given the key-value pairs of some object with 2 properties, maps a pair of values
const values = ([[, x], [, y]]) => [x, y]

// Turns an object of two properties into a pair of property values
const entry = compose (values) (Object.entries)

// Turns many objects of two properties, into an object on which
// keys are first properties' values, and vaules the second properties' values.
const keyValueObject = xs => Object.fromEntries (xs.map (entry))

const input = {
items: [{
id: '12',
value: true
}, {
id: '34',
value: true
}, {
id: '56',
value: false
}]
}

const output = keyValueObject (input.items)

console.log(output)

关于javascript - 如何遍历对象数组并制作键值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62343524/

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