我正在尝试从数组项中向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));
我的代码正在运行,但我正在寻找一种正确的方法来使用我的数组元素,因为我将拥有多个,b,c
PS:并非所有密钥都将被使用
答案 0 :(得分:1)
您可以使用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));
&#13;
答案 1 :(得分:1)
您可以迭代密钥并构建新属性。
var object = { Root: { a: "1800,1200,3100", b: "1500,1999,2001", c: "40,60,50", d: "this is not needed", e: "nor this one" } },
reference = object.Root;
Object
.keys(reference)
.forEach(k => {
var values = reference[k].split(',');
if (values.length === 1) {
return;
}
values.forEach((v, i) => {
reference['row_' + i] = reference['row_' + i] || {};
reference['row_' + i][k] = v;
});
delete reference[k];
});
console.log(object);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 2 :(得分:1)
您可以使用以下方法获得所需的结果
reduce()
match()
Object.keys()
Object.values()
<强>样本强>
const root = {
"Root": {
"a": "1800,1200,3100",
"b": "1500,1999,2001",
"c": "40,60,50",
"d": "this is not needed",
"e": "nor this one"
}
},
hash = ["a", "b", "c"],
keys = Object.keys(root.Root);
let result = Object.values(root.Root).reduce((obj, value, index) => {
if (value.match(',')) {
value = value.split(',');
obj[`row_${index}`] = hash.reduce((object, key, index) => {
object[key] = value[index];
return object;
}, {});
} else {
obj[keys[index]] = value;
}
return obj;
}, {})
console.log(result);