Home > Blockchain >  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 javascript

Time:10-28

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

example

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

CodePudding user response:

With map() and 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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can take advantage of Array.prototype.reduce to update the shape of the result array

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) => {
    acc[[currentKey]] = current[index];
    return acc;
  }, {});
  return accumulator.concat(obj);
}, []);

console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related