简体   繁体   中英

How to convert multiple arrays into one array of multiple objects?

Given the following arrays:

let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];

How to generated a new array of objects that look like that:

let z = [
    {x: a, y: e, w: i},
    {x: b, y: f, w: j},
    {x: c, y: g, w: k},
    {x: d, y: h, w: l}
];

This is what I came up so far:

for(var i; i < x.length; i++) {

    x = x[i];
    y = y[i];
    w = w[i];

    obj = {
        x: x,
        y: y,
        w: w
    };

    z = [];
    z.push(obj);
}

Thanks!

Use Array#map function and get also the index, which you will use to get the items from the second and third array. I used also || if first array has more items that the others.

 let x = ['a', 'b', 'c',' d']; let y = ['e', 'f', 'g', 'h']; let w = ['i', 'j', 'k', 'l']; let mapped = x.map((item, index) => ({ x: item, y: y[index] || '', w: w[index] || '' })); console.log(mapped); 

Try

var z = x.map( (s,i) => ({ x : x[i], y : y[i], w : w[i] }) );

Explanation

  • iterate x using map
  • for each index of x , return an object having keys as x , y and z with values from their respective index .

Demo

 var x = ['a', 'b', 'c', 'd']; var y = ['e', 'f', 'g', 'h']; var w = ['i', 'j', 'k', 'l']; var z = x.map((s, i) => ({ x: x[i], y: y[i], w: w[i] })); console.log(z); 

 let items = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l" ]; for (let i = 0; i < items.length; i++) Object.defineProperty(window, items[i], { value: items[i], writable: false }); //The code above there is just to define the variables in your arrays. let x = [a, b, c, d]; let y = [e, f, g, h]; let w = [i, j, k, l]; let keys = [ "x", "y", "w" ]; //This array contains the name for accessing to your arrays. let dimension = Math.max(...keys.map(function(array) { return eval(array).length; })); let z = new Array(dimension); for (let i = 0; i < dimension; i++) { let obj = {}; for (let ii = 0; ii < keys.length; ii++) { let key = keys[ii]; obj[key] = eval(key)[i]; } z[i] = obj; } console.log(JSON.stringify(z)); 

You can also look at this fiddle .

You can use forEach as following :

var result = [];
a.forEach((currenValue, index) => {
    result.push({x:x[index], y:b[index], w:c[index]});
});
console.log(result);

You could use an array with the keys for the object and reduce the array with the arrays.

 var x = ['a', 'b', 'c', 'd'], y = ['e', 'f', 'g', 'h'], w = ['i', 'j', 'k', 'l'], keys = ['x', 'y', 'w'], result = [x, y, w].reduce(function (r, a, i) { a.forEach(function (v, j) { r[j] = r[j] || {} r[j][keys[i]] = v; }); return r; }, []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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