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

How to modify JSON key name within an array in NodeJs

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

let rows = function1();

这里rows看起来像:

"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 个元素中 Hostname 将保留名称,

我想将 rows array 修改为如下所示:

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