I am trying to create a new object based off an existing array. I want to create a new object that show below
{ jack: 'jack', content: 'ocean'},
{ marie: 'marie', content: 'pond'},
{ james: 'james', content: 'fish biscuit'},
{paul: 'paul', content: 'cake'}
const words = ['jack','marie','james','paul'] const myUsers = [ { name: 'jack', likes: 'ocean' }, { name: 'marie', likes: 'pond' }, { name: 'james', likes: 'fish biscuits' }, { name: 'paul', likes: 'cake' } ] const usersByLikes = words.map(word => { const container = {}; container[word] = myUsers.map(user => user.name); container.content = myUsers[0].likes; return container; })
I am not getting the correct object, but instead it returns a list.
[ { jack: [ 'shark', 'turtle', 'otter' ], content: 'ocean'}, { marie: [ 'shark', 'turtle', 'otter' ], content: 'ocean' }, { james: [ 'shark', 'turtle', 'otter' ], content: 'ocean' }, { paul: [ 'shark', 'turtle', 'otter' ], content: 'ocean'} ]
What is the role of words array? I think the below code will work.
const result = myUsers.map(user => ({
[user.name]: user.name,
content: user.likes
}));
console.log('result', result);
In case, if want to filter the users in word array then below solution will work for you.
const result = myUsers.filter(user => {
if (words.includes(user.name)) {
return ({
[user.name]: user.name,
content: user.likes
})
}
return false;
});
You can achieve your need with a single loop.
The answer @aravindan-venkatesan gave should give you the result you are looking for. However important to consider:
When using .map()
javascript returns an array of the same length, with whatever transformations you told it to inside map()
.
If you want to create a brand new object, of your own construction. Try using .reduce()
. This allows you to set an input variable, ie: object, array or string.
Then loop over, and return exactly what you want, not a mapped version of the old array.
See here for more details:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
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.