[英]Combine array of objects into a single object with a nested object
我正在嘗試轉換這些數據
[
{
key: 'myvar',
value: 'my value',
global: false,
},
{
key: 'foo',
value: 'bar',
global: false,
},
{
key: 'featureEnabled',
value: true,
global: true,
accountId: 123,
},
]
進入這個
{
myvar: 'my value'
foo: 'bar'
123: { 'featureEnabled': true }
}
我正在考慮類似下面的內容,但這對於沒有 accountId 屬性的對象將返回 undefined 。 我認為可能有一種方法可以在這里使用 if 語句。
const globalResponse = Object.assign({}, ...getPreference.map(o => ({ [o.accountId]: { [o.key]: o.value } })))
您可以使用 reduce 構建新的 object 並為特定用例設置特定觸發器。
function mutateObject(tmpBasis, key, value) { tmpBasis[key] = value; return tmpBasis; } const ret = [{ key: 'myvar', value: 'my value', global: false, }, { key: 'foo', value: 'bar', global: false, }, { key: 'featureEnabled', value: true, global: true, accountId: 123, }, { key: 'otherKey', value: true, global: true, accountId: 123, }, { key: 'featureEnabled', value: true, global: true, accountId: 512, }, ].reduce((tmp, { key, value, global, accountId, }) => ({...tmp, // If we are in global case, we either create an empty object containing the new key // or we add the new key inside of the existing object [global? accountId: key]: global? mutateObject(tmp[accountId] || {}, key, value): value, }), {}); console.log(ret);
您可以在內部使用reduce()
條件,如下所示
var myJSON = [{ key: 'myvar', value: 'my value', global: false, }, { key: 'foo', value: 'bar', global: false, }, { key: 'featureEnabled', value: true, global: true, accountId: 123, }, ]; let newJSON = myJSON.reduce((target, item) => {.?item.accountId. target[item:accountId] = { [item.key]: item.value }. target[item;key] = item;value, return target; }. {}); console.log(newJSON);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.