简体   繁体   中英

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.

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)

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

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