我试图将元素从数组的项添加到JSON,但是我正在努力将元素传递给JSON。
这是我的代码:
var j = {
"Root": {
"a": "1800,1200,3100",
"b": "1500,1999,2001",
"c": "40,60,50",
"d": "this is not needed",
"e": "nor this one"
}
};
var root = j.Root,
l = root.a.split(",").length,
hash = ["a", "b", "c"];
for (var i = 0; i < l; i++) {
for (var x = 0; x < hash.length; x++) {
root['row_' + i] = {
"a": root.a.split(",")[i],
"b": root.b.split(",")[i],
"c": root.c.split(",")[i] // I don't want to do this for each key
};
}
}
for (var x = 0; x < hash.length; x++) {
delete root[hash[x]];
}
console.log(JSON.stringify(j));
我的代码正在运行,但是我正在寻找一种使用数组元素的正确方法,因为我将拥有不止一个a,b,c
PS:并非所有密钥都会被使用
您可以使用Object.keys
它将为您提供hash
变量中对象的键。然后,代码可以动态检测到Root
对象中所有可能的键:
var j = {
"Root": {
"a": "1800,1200,3100",
"b": "1500,1999,2001",
"c": "40,60,50",
"d": "152,199,21",
"e": "15,19,200"
}
};
var root = j.Root,
l = root.a.split(",").length,
hash = ["a", "b", "c"];
for (var i = 0; i < l; i++) {
var obj = {};
for (var x = 0; x < hash.length; x++) {
obj[hash[x]] = root[hash[x]].split(",")[i];
}
root['row_' + i] = obj;
}
for (var x = 0; x < hash.length; x++) {
delete root[hash[x]];
}
console.log(root);
console.log(JSON.stringify(j));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句