Combine multiple arrays into an array of objects in JavaScript

Let's say I have three arrays that display some names, the number of books read, and how large these people are [in names]:

let names = ["Mary", "Joe", "Kenan"];
let numberOfBooks = [2, 1, 4];
let awesomenessLevel = ["pretty cool", "meh", "super-reader"];

I am trying to use .reduce()to combine them to create an array of objects containing the corresponding index in each array, but I fail:

    let people = [
    {
       name: "Mary",
       noOfBooks: 2,
       awesomeness: "pretty cool"
    },
    {
       name: "Joe",
       noOfBooks: 1,
       awesomeness: "meh"
    },
    {
       name: "Kenan",
       noOfBooks: 4,
       awesomeness: "super-reader"
    }
  ]

I got it with a decrease:

let arrFinal = [];

 names.reduce(function(all, item, index) {
  arrFinal.push({
    name: item,
    noOfBooks: numberOfBooks[index],
    awesomeness: awesomenessLevel[index]
  })
}, []);
+6
source share
3 answers

You can do this with mapfor example:

let result = names.map( (v, i) => ({
    name: names[i], 
    noOfBooks: numberOfBooks[i],
    awesomenessLevel: awesomenessLevel[i]
}));

let names = ["Mary", "Joe", "Kenan"];
let numberOfBooks = [2, 1, 4];
let awesomenessLevel = ["pretty cool", "meh", "super-reader"];

let result = names.map( (v, i) => ({
    name: names[i], 
    noOfBooks: numberOfBooks[i],
    awesomenessLevel: awesomenessLevel[i]
}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run codeHide result

map , reduce , , ( ), , . map.

+6

map 1--1 .

let people = names.map(function (e, i) {
    return {name:e, noOfBooks:numberOfBooks[i],awesomeness: awesomenessLevel[i]};
});

let names = ["Mary", "Joe", "Kenan"];
let numberOfBooks = [2, 1, 4];
let awesomenessLevel = ["pretty cool", "meh", "super-reader"];

let people = names.map(function (e, i) {
    return {name:e, noOfBooks:numberOfBooks[i],awesomeness: awesomenessLevel[i]};
});


console.log(people);
Hide result
+5

You can use the dynamic approach by combining all arrays with one object and using key names as property names for the result objects in the array

let names = ["Mary", "Joe", "Kenan"],
    numberOfBooks = [2, 1, 4],
    awesomenessLevel = ["pretty cool", "meh", "super-reader"],
    object = { name: names, noOfBooks: numberOfBooks, awesomeness: awesomenessLevel },
    result = Object.keys(object).reduce((r, k) =>
        (object[k].forEach((a, i) =>
            (r[i] = r[i] || {})[k] = a), r), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1016331/


All Articles