簡體   English   中英

如何遍歷對象數組並制作鍵值對?

[英]How to loop through array of objects and make key value pairs?

我有一個這樣的對象數組:

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

}

我想將此添加到現有的 object 中,其中 id 是此 object 的鍵,如下所示:

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 將它們轉換為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)

您可以從項目中迭代每個項目並創建一個新的 object,如下所示。

 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);

使用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));

首先,您可以將itens轉換為“KV”條目

> someObj.items.map(({id, value}) => [id, value])
[ [ '12', true ], [ '34', true ], [ '56', false ] ]

然后變成Object

> Object.fromEntries(someObj.items.map(({id, value}) => [id, value]))
{ '12': true, '34': true, '56': false }

你可以做一個 function

> 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' }

然后您的 function 將適用於任何iterable

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM