gpt4 book ai didi

javascript - 如何在 NodeJs 中修改数组中的 JSON 键名称

转载 作者:行者123 更新时间:2023-12-02 20:57:03 50 4
gpt4 key购买 nike

我在 NodeJS 中有一个函数,它返回 JSON 元素数组

let rows = function1();

这里的看起来像:

"rows": [
{
"Hostname": "abc123",
"name": "name1",
"Status": "PASS",
"Heading": "Not Applicable"
},
{
"Hostname": "abc123",
"name": "name2",
"Status": "FAIL",
"Heading": "Not Applicable"
}
]

这里,rows 可以有任意数量的 Json 元素:

"rows": [
{
"Hostname": "abc123",
"name": "name1",
"Status": "PASS",
"Heading": "Not Applicable"
},
{
"Hostname": "abc123",
"name": "name2",
"Status": "FAIL",
"Heading": "Not Applicable"
},
{
"Hostname": "abc123",
"name": "name3",
"Status": "FAIL",
"Heading": "Not Applicable"
},
...
]

在所有 JSON 元素中,主机名 将保留名称,

我想修改行数组,使其如下所示:

"rows": [
{
"Hostname": "abc123",
"name1Status": "PASS",
"name1Heading": "Not Applicable"
"name2Status": "FAIL",
"name2Heading": "Not Applicable"
"name3Status": "FAIL",
"name3Heading": "Not Applicable"
...
]

最佳答案

如果你理解正确的话,那么你需要达到这个结果。为此使用reduce,对于处理数组非常方便

const rows = [
{
"Hostname": "abc123",
"name": "name1",
"Status": "PASS",
"Heading": "Not Applicable"
},
{
"Hostname": "abc123",
"name": "name2",
"Status": "FAIL",
"Heading": "Not Applicable"
}
]
const res = rows.reduce((acc, rec) => {
let result = { ...acc, [`Hostname`]: rec.Hostname, [`${rec.name}Status`]: rec.Status, [`${rec.name}Heading`]: rec.Heading }
return result
}, [])
console.log(res)

关于javascript - 如何在 NodeJs 中修改数组中的 JSON 键名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61451521/

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