欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js合并两个数组生成合并后的key:value数组

程序员文章站 2022-03-14 18:27:14
核心代码 // var activesubjectsname = ["语文", "数学", "英语", "思想品德", "科学"]; // var active...

核心代码

// var activesubjectsname = ["语文", "数学", "英语", "思想品德", "科学"];
// var activesubjectsnum = [46, 2, 2, 28, 29];
// var activesubjectsarr = [];

for (var i = 0; i < activesubjectsname.length; i++) {
 console.log(i);
 var activesubjectsobject = {};
 for (var j = 0; j < activesubjectsnum.length; j++) {
  if (i == j) {
   activesubjectsobject.name = activesubjectsname[i];
   activesubjectsobject.value = activesubjectsnum[j];
   activesubjectsarr.push(activesubjectsobject);
  }
 }
}
console.log(activesubjectsarr);
// activesubjectsarr=[
// {name: "语文", value: 46},
// {name: "数学", value: 2},
// {name: "英语", value: 2},
// {name: "思想品德", value: 28},
// {name: "科学", value: 29}
// ]

原理就是将两个数组结合到一个数组里面,跟json对照关系一样,需要的朋友可以参考一下,注意两个数组按顺序对应好即可。