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

问题描述 投票:0回答:1

我在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"
     ...
]
javascript arrays node.js javascript-events node-modules
1个回答
1
投票

如果你理解正确,那么你需要实现这个结果。使用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)
© www.soinside.com 2019 - 2024. All rights reserved.