简体   繁体   中英

JavaScript: Pick old array by key and rename the key in new array

I have an array of objects and I want to "pick" a new array from the value of the key viewerId . I also want to change the name of the viewerId key to userId . Here is what I have done with lodash:

 const viewerList = [{ "id": 1, "viewerId": 5, "status": true }, { "id": 2, "viewerId": 8, "status": true }, { "id": 3, "viewerId": 6, "status": true }, { "id": 4, "viewerId": 9, "status": true } ] var result = [] _.each(viewerList, (o) => { result.push(_.pick(o, 'viewerId')) }) result = result.map(function(item) { return { userId: item.viewerId } }); console.log(result)
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

I am doing this in two steps. Can this be optimized?

You could do the following in a single statement:

 const viewerList = [{ "id": 1, "viewerId": 5, "status": true }, { "id": 2, "viewerId": 8, "status": true }, { "id": 3, "viewerId": 6, "status": true }, { "id": 4, "viewerId": 9, "status": true } ] // The same logic in a single statement var result = viewerList.map(function(item) { return { userId : item.viewerId} }) console.log(result)

This work on all browsers ie9 and up. For more information on the .map() function being used, see this

For this purpose, using map would be the proper way to handle it, as you are transforming the existing data.

Therefore, you don't even need lodash .

You can take advantage of destructuring and renaming in the same step:

const result = viewerList.map(({ viewerId: userId }) => ({ userId }))

you can use this

viewerList.map(({viewerId}) => ({userId: viewerId}))

or in lodash

_.map(viewerList, ({viewerId}) => ({userId: viewerId}))

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