JrmDel
JrmDel

Reputation: 462

How to map values from an array to an array of Object?

I have two arrays of the same size. The first one is an array of object, and the second one, an array of number. I am looking for an elegant way to map values of the second array on a new field of each object of the first array. Here is my code :

// Let's say that after my back-end request, I end up with these arrays
let promises = [{data: {count:56}}, {data: {count:29}}]
let users = [{id:1, name:'Alice'}, {id:2, name: 'Bob'}]

// I'd like to add the 'count' value to each user
users.map((user,index) => user.newField = promises[index].data.count)
// Expected output : [{id:1, name:'Alice', newField:56}, {id:2, name: 'Bob', newField:29}]
console.log(users)

Edit

Actually, while copying and changing a bit my code, I found my error. If someone has a cleaner way of doing it, I'd be glad to see it. I think it may help so I publish it anyway.

Upvotes: 0

Views: 49

Answers (2)

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6390

I think you want something like this-

let promises = [{data: {count:56}}, {data: {count:29}}]
let users = [{id:1, name:'Alice'}, {id:2, name: 'Bob'}];
const newUsers = users.map((value, index) => {
    value.count = promises[index].data.count;
    return value;
});

console.log(newUsers);

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36564

Your way is completely fine but I would like to use map() in a proper way and donot mutate the original data.

let promises = [{data: {count:56}}, {data: {count:29}}]
let users = [{id:1, name:'Alice'}, {id:2, name: 'Bob'}]
const res = users.map((x, i) => ({...x, newField: promises[i].data.count}));
console.log(res)

You can use forEach on promises and use destrucuting syntax

let promises = [{data: {count:56}}, {data: {count:29}}]
let users = [{id:1, name:'Alice'}, {id:2, name: 'Bob'}]
promises.forEach(({data: {count}}, i) => users[i].newField = count )
console.log(users)

Upvotes: 3

Related Questions