我有四个数组:
var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];
如何在Nodejs中将它们合并为一个类似字符串的json?
[{"a":1,"b":34,"c":22,"d":14},
{"a":2,"b":55,"c":23,"d":78},
{"a":3,"b":66,"c":53,"d":98}]
这是我的代码,但是有人有更好的解决方案吗?我确实需要保留报价。
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];
var obj = "[";
for (var u = 0; u < a.length; u++) {
var l = "\"a\":"+a[u]+",";
var m = "\"b\":"+b[u]+",";
var q = "\"b\":"+c[u]+",";
var n = "\"d\":"+d[u]+"";
if(u == (a.length-1))
var k = "{" + l + m + q + n + "}";
else
var k = "{" + l + m + q + n + "},";
console.log(k);
obj = obj + k;
};
obj = obj + "]";
console.log(obj);
&#13;
答案 0 :(得分:1)
假设所有数组的长度相同,并对其名称进行硬编码:
var obj = []
for (var u = 0; u < a.length; u++) {
obj.push({
'a': a[u],
'b': b[u],
'c': c[u],
'd': d[u]
});
};
obj = JSON.stringify(obj);
编辑:将obj转换为json字符串,该问题被错误地编辑以询问数组。
答案 1 :(得分:0)
这段代码可以解决问题:
var arrays = [a, b, c, d]; // add all the arrays you want
var num = a.length; // or hardcode to the length you want
var result = [];
for(var i = 0; i < num; i++) {
var element = {};
attributes.forEach(function(attr, index) {
element[attr] = arrays[index][i];
});
result.push(element);
}
var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];
var arrays = [a, b, c, d];
var result = [];
var num = a.length;
for(var i = 0; i < num; i++) {
var element = {};
attributes.forEach(function(attr, index) {
element[attr] = arrays[index][i];
});
result.push(element);
}
document.write(JSON.stringify(result));
&#13;
答案 2 :(得分:0)
var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];
var x = [];
for (var i=0;i<3;i++) {
var obj = {};
for (var j=0;j<attributes.length;j++){
obj[attributes[j]]=eval(attributes[j]+"["+i+"]");
}
x.push(obj);
}
console.log(x);
答案 3 :(得分:0)
我知道这个问题已有多个答案,但似乎没有人处理关键数组,因为变量的名称是在属性数组中引入的。由于我认为这是属性数组的要点,我的解决方案就是使用节点的全局范围。它也不假设所有的键数组都与未指定的相同(即使它们是示例)。
var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];
var arr = [];
while(true){
var obj = {};
for(var i=0;i<attributes.length;i++){
if(global[attributes[i]].length)obj[attributes[i]]=global[attributes[i]].shift();
}
if(Object.keys(obj).length)
arr.push(obj);
else
break;
}
在下面的小提琴中,我不得不通过手动创建全局数组来模拟节点的全局范围,但是你明白了这一点:
小提琴:https://jsfiddle.net/trex005/vm1yeL5d/
重要提示如果数组实际上不在全局范围内,但在某些其他对象中,则可以使用该对象代替global