简体   繁体   English

如何将数组中的值映射到对象数组?

[英]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.你的方式完全没问题,但我想以适当的方式使用map()并且不要改变原始数据。

 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您可以在promises上使用forEach并使用解构语法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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