简体   繁体   English

如何基于数组和另一个对象创建新对象?

[英]how do i create a new object based off an array and another object?

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. @aravindan-venkatesan 给出的答案应该会给你你正在寻找的结果。 However important to consider:但重要的是要考虑:

When using .map() javascript returns an array of the same length, with whatever transformations you told it to inside map() .使用.map() javascript 返回一个长度相同的数组,以及你告诉它在map()内部进行的任何转换。

If you want to create a brand new object, of your own construction.如果你想创建一个全新的对象,你自己的构造。 Try using .reduce() .尝试使用.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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

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

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