我想将两个数组转换为另一种数组格式。
这是我的代码:
var array1 = [ "Kolkata", "Begumpet", "Bellary"];
var array2 = [[[20,"Kolkata1"],[10,"Kolkata2c"]],
[[0,"Begumpet1"],[10, "Begumpet2e"]],
[[30, "Bellary1"],[0, "Bellary2a"]]]
console.log(array2);
var resultvalue = [];
for (i = 0; i < array2.length; i++) {
var result = "";
var m = 0;
for (j = 0; j < array2[i].length; j++) {
if(m==0){
result += "label: '" + array1[i] + "',";
m++;
}
result += " '" + array2[i][j][1] + "': " + array2[i][j][0] + ", ";
}
resultvalue.push(result);
}
console.log(resultvalue);
它正在产生我想要的东西,除了结果是一个字符串,而我需要实际的数组。
预期的输出对象应该是这样的:
dataset = [
{label:"Kolkata", "Kolkata1":20, "Kolkata2c":10},
{label:"Begumpet", "Begumpet1":0, "Begumpet2e":10},
{label:"Bellary", "Bellary1":30, "Bellary2a":0},
];
答案 0 :(得分:2)
您可以迭代array2
并为每个条目映射一个新对象。
var array1 = ["Kolkata", "Begumpet", "Bellary"],
array2 = [[[20, "Kolkata1"], [10, "Kolkata2c"]], [[0, "Begumpet1"], [10, "Begumpet2e"]], [[30, "Bellary1"], [0, "Bellary2a"]]],
dataset = array2.map(function (a, i) {
var o = { label: array1[i] };
a.forEach(function (b) {
o[b[1]] = b[0];
});
return o;
});
console.log(dataset);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 1 :(得分:1)
使用内部数组上的Array.prototype.reduce
和forEach
获取所需数组的另一种解决方案 - 演示如下:
var array1 = [ "Kolkata", "Begumpet", "Bellary"];
var array2 = [[[20,"Kolkata1"],[10,"Kolkata2c"]],[[0,"Begumpet1"],[10, "Begumpet2e"]],[[30, "Bellary1"],[0, "Bellary2a"]]];
var result = array2.reduce(function(p,c,i){
var elem = {label : array1[i]};
c.forEach(e => elem[e[1]] = e[0]);
p.push(elem);
return p;
},[]);
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
答案 2 :(得分:1)
您可以使用此ES6代码执行此操作:
var array1 = [ "Kolkata", "Begumpet", "Bellary"];
var array2 = [[[20,"Kolkata1"],[10,"Kolkata2c"]],
[[0,"Begumpet1"],[10, "Begumpet2e"]],[[30, "Bellary1"],[0, "Bellary2a"]]]
var result = array2.map( (pairs, i) =>
Object.assign ({ label: array1[i] }, ...pairs.map ( ([v, k]) => ({ [k]: v }))));
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 3 :(得分:1)
根据JSON结构的最佳实践,您所需的输出JSON对象中存在一些更正。所以根据我认为有效的,这是正确的代码。
此外,我使用JSON.stringify()来打印JSON对象。
我还修改了构建输出JSON对象的方式。
var array1 = ["Kolkata", "Begumpet", "Bellary"];
var array2 = [
[
[20, "Kolkata1"],
[10, "Kolkata2c"]
],
[
[0, "Begumpet1"],
[10, "Begumpet2e"]
],
[
[30, "Bellary1"],
[0, "Bellary2a"]
]
];
var resultvalue = [];
for (i = 0; i < array1.length; i++) {
var result = {};
var temp = {};
temp.label = array1[i];
for (j = 0; j < 2; j++) {
temp[[array2[i][j][1]]] = array2[i][j][0];
}
resultvalue.push(temp);
}
document.write(JSON.stringify(resultvalue));
console.log(resultvalue);
&#13;
抱歉......我们理解了这个问题...我更新了这个代码。
答案 4 :(得分:0)
要将javascript对象转换为JSON,您必须调用JSON.stringify
方法。
var jsonString = JSON.stringify(array2);