[英]JSON Object property into JSON Object name
I have a JSON file with a lot of objects like this (eg properties of Pikemen unit >Heroes 3 btw<):我有一个 JSON 文件,其中包含很多这样的对象(例如 Pikemen 单位的属性>Heroes 3 btw<):
[ {
"ID": 0,
"AI": 80,
"": null,
"Level": 0,
"Growth": 14,
"Low": 20,
"High": 50,
"Town": 0,
"Name": "Pikeman",
}, etc.. ]
How could I make "Name"
property the name of every object in my JSON file?如何使
"Name"
属性成为我的 JSON 文件中每个 object 的名称? Either in JS code or through formatting file.在 JS 代码中或通过格式化文件。 What I mean is:
我的意思是:
[ "Pikeman": {
"ID": 0,
"AI": 80,
etc..
} ]
Use it like this:像这样使用它:
let obj = [{
"ID": 0,
"AI": 80,
"": null,
"Level": 0,
"Growth": 14,
"Low": 20,
"High": 50,
"Town": 0,
"Name": "Pikeman",
},{
"ID": 0,
"AI": 82220,
"": null,
"Level": 230,
"Growth": 14,
"Low": 20213,
"High": 12312050,
"Town": 10,
"Name": "Pikeman2",
}]
obj.forEach((item, index) => {
obj[item.Name] = item;
delete obj[index];
})
console.log(obj)
Hi @Adrian You can iterate through your array and obtain the name and assign int as a key check this:嗨@Adrian您可以遍历您的数组并获取名称并将int指定为键检查:
let obj = [ {
"ID": 0,
"AI": 80,
"": null,
"Level": 0,
"Growth": 14,
"Low": 20,
"High": 50,
"Town": 0,
"Name": "Pikeman",
},
{
"ID": 0,
"AI": 80,
"": null,
"Level": 0,
"Growth": 14,
"Low": 20,
"High": 50,
"Town": 0,
"Name": "Pikeman1",
},
{
"ID": 0,
"AI": 80,
"": null,
"Level": 0,
"Growth": 14,
"Low": 20,
"High": 50,
"Town": 0,
"Name": "Pikema2",
}]
let objConverted = {};
obj.forEach( o => {
objConverted[o.Name] = o;
} )
console.log(objConverted);
Check this if you wanna play with the code: https://repl.it/repls/HalfSatisfiedMainframe如果您想使用代码,请检查此: https://repl.it/repls/HalfSatisfiedMainframe
try: let obj = {};尝试:让 obj = {}; obj['Pikeman'] = { "ID": 0, "AI": 80, etc.. }
obj['Pikeman'] = { "ID": 0, "AI": 80, etc.. }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.