0

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.

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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);

2 Comments

This is not proper way to use map(). You should mutate the original object while using map() if you want to mutate original data better option is to use forEach(). Your code doesn't make because it mutates the original data and also returns a new data
Thank you @MaheerAli.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.