Home > front end >  How to connect 2 arrays into object?
How to connect 2 arrays into object?

Time:02-10

I have this array ['x','y','z'] and it can have arbitrary number of elements, and second array of numbers [2,4,5,6,7,8,0,0,9] and I need to map them into object so we get something like [{x:2,y:4,z:5},{x:6,y:7,z:8},{x:0,y:0,z:9}]. And always Arr2.length%Arr1.length=0 How can I do it with map?

CodePudding user response:

It loops thru the values array as many times as the keys array fits inside the values array and creates a new array with those keys and values, and then combines the new smaller arrays into a big one.

var keys = ['x','y','z']
var values = [2,4,5,6,7,8,0,0,9]

const bigresult = [];
var multi = values.length/keys.length;
for (let ia = 0; ia < multi; ia  ) {
  var result = {};
  keys.forEach((key, i) => result[key] = values[i multi*ia]);
  bigresult.push(result); 
}
console.log(bigresult);

CodePudding user response:

Map isn't the right thing to use here. Map will produce an array of the same length as the array you call it on. You want an array of length Arr2.length / Arr1.length. Your desired array contains objects with a parameter for each member of Arr1 but again map will output an array not an object.

Here is a solution:

var Arr1 = ['x','y','z'];
var Arr2 = [2,4,5,6,7,8,0,0,9];
var Arr3 = makeArrayOfObjects(Arr1, Arr2);

console.log(Arr3);

function makeArrayOfObjects(Arr1, Arr2){
    if (0 != Arr2.length % Arr1.length){
        // error handling code
        return false;
    }
    var Arr3 = [];
    var i = 0;
    while (Arr2.length > 0){
        Arr3[i] = {};
        for (const a1 of Arr1) {
            Arr3[i][a1] = Arr2.shift();
        }
        i  ;
    }
    return Arr3;
}

Output:

[{x: 2, y: 4, z: 5},{x: 6, y: 7, z: 8},{x: 0, y: 0, z: 9}]
  •  Tags:  
  • Related