-
慕斯王
您可以通过以下方式实现您的目标:Array#reduceconst 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#mapObject.fromPairsconst 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)
-
九州编程
您可以从项中循环访问每个项并创建一个新对象,如下所示。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);
-
宝慕林4294392
使用和将简化。mapObject.valuesconst 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));
-
慕沐林林
首先,您可以将它转换为“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