gpt4 book ai didi

javascript - 使用 Lodash 转换对象数组

转载 作者:行者123 更新时间:2023-12-02 07:22:49 27 4
gpt4 key购买 nike

我正在尝试简化复杂的结构。
我尽可能地简化了它并将其简化为:

[
{'Cells':{'Results':[
{'Key':'ID','Value':123},
{'Key':'Color','Value':'Red'},
{'Key':'Direction','Value':'West'}
]}},
{'Cells':{'Results':[
{'Key':'ID','Value':456},
{'Key':'Color','Value':'Green'},
{'Key':'Direction','Value':'East'}
]}}
]

我的 lodash 缺乏技能,我需要帮助将上面的内容变成这样:

[
{'ID':123, 'Color':'Red', 'Direction':'West'},
{'ID':456, 'Color':'Green', 'Direction':'East'}
]

顺便说一下,键的数量因对象而异。至少,它可能只有 ID,但有些可能不止示例中的这三个。

最佳答案

在普通的 Javascript 中,你可以使用两个嵌套循环。

var array = [{ 'Cells': { 'Results': [{ 'Key': 'ID', 'Value': 123 }, { 'Key': 'Color', 'Value': 'Red' }, { 'Key': 'Direction', 'Value': 'West' }] } }, { 'Cells': { 'Results': [{ 'Key': 'ID', 'Value': 456 }, { 'Key': 'Color', 'Value': 'Green' }, { 'Key': 'Direction', 'Value': 'East' }] } }],
condensed = array.map(function (a) {
var o = {};
a.Cells.Results.forEach(function (b) {
o[b.Key] = b.Value;
});
return o;
});

console.log(condensed);

关于javascript - 使用 Lodash 转换对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38205498/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com