4 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
您可以通過以下方式實(shí)現(xiàn)您的目標(biāo):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)
另外,也許最簡(jiǎn)單的方法可能是使用將對(duì)象轉(zhuǎn)換為對(duì),然后使用將它們轉(zhuǎn)換為對(duì)象:Array#mapObject.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)
最后,這是一個(gè)功能方法:
// 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)

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以從項(xiàng)中循環(huán)訪問每個(gè)項(xiàng)并創(chuàng)建一個(gè)新對(duì)象,如下所示。
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);

TA貢獻(xiàn)2021條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用和將簡(jiǎn)化。mapObject.values
const output = arr => Object.fromEntries(arr.map(Object.values));
let someObj = {
items: [
{
id: "12",
value: true,
},
{
id: "34",
value: true,
},
{
id: "56",
value: false,
},
],
};
console.log(output(someObj.items));

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
首先,您可以將它轉(zhuǎn)換為“KV”條目
> someObj.items.map(({id, value}) => [id, value])
[ [ '12', true ], [ '34', true ], [ '56', false ] ]
然后將其轉(zhuǎn)換為對(duì)象
> Object.fromEntries(someObj.items.map(({id, value}) => [id, value]))
{ '12': true, '34': true, '56': false }
你可以做一個(gè)函數(shù)
> let ObjectFromMapping = (vs, mapping) => Object.fromEntries(vs.map(mapping))
> ObjectFromMapping(someObj.items, ({id, value}) => [id, value])
{ '12': true, '34': true, '56': false }
也許變成一個(gè)可迭代的是一個(gè)好主意vs
> let ObjectFromMapping = (vs, mapping) => Object.fromEntries([... vs].map(mapping))
> ObjectFromMapping("abc", (char, idx) => [idx, char])
{ '0': 'a', '1': 'b', '2': 'c' }
然后,您的函數(shù)將適用于任何iterable
添加回答
舉報(bào)