我有一个这样的对象数组:
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,
}
答案 0 :(得分:3)
您可以使用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)
答案 1 :(得分:1)
您可以从项目中迭代每个项目并创建一个新对象,如下所示。
let someObj = {
items: [{
id: '12',
value: true
}, {
id: '34',
value: true
}, {
id: '56',
value: false
}]
}
const newObj = {};
someObj.items.map(item =>{
newObj[item.id]= item.value;
});
console.log(newObj);
答案 2 :(得分:1)
使用46436664
和46436663
将会简化。
rownum
答案 3 :(得分:0)
首先,您可以将iten转换为“ KV”条目
> someObj.items.map(({id, value}) => [id, value])
[ [ '12', true ], [ '34', true ], [ '56', false ] ]
然后将其转换为对象
> Object.fromEntries(someObj.items.map(({id, value}) => [id, value]))
{ '12': true, '34': true, '56': false }
您可以执行功能
> let ObjectFromMapping = (vs, mapping) => Object.fromEntries(vs.map(mapping))
> ObjectFromMapping(someObj.items, ({id, value}) => [id, value])
{ '12': true, '34': true, '56': false }
也许将vs
变成可迭代对象是个好主意
> let ObjectFromMapping = (vs, mapping) => Object.fromEntries([... vs].map(mapping))
> ObjectFromMapping("abc", (char, idx) => [idx, char])
{ '0': 'a', '1': 'b', '2': 'c' }
然后您的函数将在任何iterable
上运行