【发布时间】:2018-09-18 18:05:31
【问题描述】:
我正在尝试将元素从数组的项中添加到 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:并非所有密钥都会被使用
【问题讨论】:
-
There's no such thing as a "JSON Object" 你拥有的是一个 JavaScript 对象。
-
数组在哪里?您的预期输出是什么?
-
@phuzi,谢谢你的评论,你能帮忙吗?
-
@AnkitAgarwal 数组是散列,我的预期输出是正确的,但我不想明确命名循环中的每个元素
-
@Jonathan 好的,我已经添加了答案
标签: javascript jquery arrays json dictionary