简体   繁体   English

javascript中两个数组合并形成新的键值对数组

[英]Two array merge to form new array of key value pairs in javascript

Array a=['india','germany','russia'];
Array b=[100,70,60];
Array c =[
{Country:"india", val:100},
{Country:"germany", val:70},
{Country:"russia", val:60},];

i want the result array like Array c.我想要像数组 c 这样的结果数组。

a=['india','germany','russia'];
b=[100,70,60];
const c=[]
for(var i=0;i<a.length;i++){
data={
"Country":a[i],
"val":b[i]
}
c.push(data)
}
console.log(c)
let a=['india','germany','russia'];
let b=[100,70,60];
let c=a.map((country,index)=>{
    return {
        "Country":country,
        "val":b[index]
    };
});

This code loops through the first array, (In case the number of elements are different for both arrays, use the array with smallest length or use default value) and sets the value of the array as the object with those properties.此代码循环遍历第一个数组,(如果 arrays 的元素数量不同,请使用长度最小的数组或使用默认值)并将数组的值设置为具有这些属性的 object。

 let a=['india','germany','russia']; let b=[100,70,60]; let c = []; for(let i in a) { c.push({country: a[i], val: b[i]}); } console.log(c);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM