[英]adding json key names to a json values and changing key names
I have a json string that is in the format:我有一个格式为 json 的字符串:
[
{
clientIDs:
"WELL #6",
analyteIDs:
[
"7440-62-2",
"7440-28-0"
]
}
]
I need to convert this to:我需要将其转换为:
[
{
header:
"WELL #6",
items:
[
header: "7440-62-2",
header: "7440-28-0"
]
}
]
The values without a key name are throwing me off.没有键名的值让我失望。
Unfortunately js cannot store a key value arrays, instead you have to use an object storing key and value.不幸的是,js 无法存储键值 arrays,而是您必须使用 object 存储键和值。 So the closes result you can achieve is following:
因此,您可以实现的关闭结果如下:
[ { header: "WELL #6", items: [ { header: "7440-62-2" }, { header: "7440-28-0" } ] } ]
For that your steps will be following:为此,您的步骤如下:
const myObjects = [ { clientIDs: "WELL #6", analyteIDs: [ "7440-62-2", "7440-28-0" ] } ] myObjects.map((myObj) => { myObj['header'] = myObj.clientIDs; myObj['items'] = myObj.analyteIDs.map((item) => { return { header: item } }); // Keep in mind, if keys are dynamic and does not exist in some objects then this will fail delete myObj['clientIDs']; delete myObj['analyteIDs']; }); console.log(myObjects);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.