简体   繁体   English

如何从两个不同长度的数组javascript创建对象数组

[英]How to create array of object from two different length of array javascript

How to create array of object from two different length of array如何从两个不同长度的数组创建对象数组

for example例如

arr1 = ["first","second","third","fourth","fifth","Sixth"]
arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]]

finalArray = [{
   first:1,
   second:2
   third:3,
   fourth:4,
   fifth:5,
   sixth:6
},{
   first:7,
   second:8
   third:9,
   fourth:10,
   fifth:11,
   sixth:12
}]

I tried this using map but getting every key value pair as whole object我尝试使用 map 但将每个键值对作为整个对象

example例子

[
 {first: 1}
 {second: 2}
 {third: 3}
 {fourth: 4}
]

With map() and reduce() :使用map()reduce()

 const arr1 = ["first", "second", "third", "fourth", "fifth", "Sixth"]; const arr2 = [["1", "2", "3", "4", "5", "6"], ["7", "8", "9", "10", "11", "12"], ["1", "2", "3", "4"]]; const res = arr2.map(v => v.reduce((a, v, i) => ({...a, [arr1[i]]: v}), {})); console.log(res);

You can take advantage of Array.prototype.reduce to update the shape of the result array你可以利用Array.prototype.reduce来更新结果数组的形状

 let arr1 = ["first","second","third","fourth","fifth","Sixth"]; let arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]]; let result = arr2.reduce((accumulator, current) => { let obj = arr1.reduce((acc, currentKey, index) => { if(current.indexOf(index) && current[index] !== undefined ){ acc[[currentKey]] = current[index]; } return acc; }, {}); return accumulator.concat(obj); }, []); console.log(result);

without reduce() and covered edge case when the arr1 contains fewer elements as the element from arr2arr1包含更少的元素作为来自arr2的元素时,没有reduce()和覆盖边缘情况

 const arr1 = ["first","second","third","fourth","fifth","Sixth"] const arr2 = [["1","2","3","4","5","6"],["7","8","9","10","11","12"],["1","2","3","4"]] const res = arr2.map(values => { const res = {} for(const [index, value] of arr1.entries()){ if(values[index]) { res[value] = values[index] // or parseInt(values[index]) } else { break } } return res }) console.dir(res)

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

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