gpt4 book ai didi

javascript - 映射Json形成数组

转载 作者:行者123 更新时间:2023-11-30 09:35:22 25 4
gpt4 key购买 nike

下面是我的json

"Issues": [
{
"Id": null,
"Key": "Project20",
"Values": [
{
"Key": "Display Name",
"Value": "Rya"
},
{
"Key": "UserName",
"Value": "RH"
},
{
"Key": "Count",
"Value": "350"
}
]
},
{
"Id": null,
"Key": "Project30",
"Values": [
{
"Key": "Display Name",
"Value": "Mike"
},
{
"Key": "UserName",
"Value": "ML"
},
{
"Key": "Count",
"Value": "90"
}
]
}
]

我需要映射这个 Json 以形成下面的数组

{ "Display Name": 'Rya', "UserName" : "RH", value: 350, url: "Project20" },
{ "Display Name": 'Mike', "UserName" : "ML", value: 90, url:"Project30" }

基本上,我还需要在我的数组中获取 key 。

我试过了

Issues.map(o => o.Values.reduce((acc, {Key, Value}) => (acc[Key] = Value, acc), {}));

这给了我

{ "Display Name": 'Rya', "UserName" : "RH", value: 350 },
{ "Display Name": 'Mike', "UserName" : "ML", value: 90 }

但我还需要数组中的 Key 字段

最佳答案

使用reduce 的初始值参数。所以不是 {} 传递 { url: o.Key }:

Issues.map(o => o.Values.reduce((acc, {Key, Value}) => (acc[Key] = Value, acc),
{ url: o.Key }));

对于那些在 IE 上的用户,您需要使用兼容 ES5 的语法:

Issues.map(function (o) {
return o.Values.reduce(function (acc, pair) {
acc[pair.Key] = pair.Value;
return acc;
}, { url: o.Key });
});

var Issues = [
{
"Id": null,
"Key": "Project20",
"Values": [
{
"Key": "Display Name",
"Value": "Rya"
},
{
"Key": "UserName",
"Value": "RH"
},
{
"Key": "Count",
"Value": "350"
}
]
},
{
"Id": null,
"Key": "Project30",
"Values": [
{
"Key": "Display Name",
"Value": "Mike"
},
{
"Key": "UserName",
"Value": "ML"
},
{
"Key": "Count",
"Value": "90"
}
]
}
];

var result = Issues.map(function (o) {
return o.Values.reduce(function (acc, pair) {
acc[pair.Key] = pair.Value;
return acc;
}, { url: o.Key });
});

console.log(result);

关于javascript - 映射Json形成数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43856421/

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