简体   繁体   English

根据另一个对象数组的值创建对象数组

[英]Create object array based on value of another object array

I've got an object array like this:我有一个这样的对象数组:

const user = [
  { name: 'Bob' },
  { name: 'Frank' }
]

But I need to get an array like this:但我需要得到一个这样的数组:

const result = [
  { key: 'Bob', value: 'Bob', text: 'Bob' },
  { key: 'Frank', value: 'Frank', text: 'Frank' }
]

I'm doing it this way:我是这样做的:

const result = []
user && user.length > 0 && user.map(u => {
  result.push({ key: u.name, value: u.name, text: u.name })
})

But is there another way to do this a bit more straight?但是还有另一种方法可以更直接地做到这一点吗? Do I really need to build each object and push it into a new array?我真的需要构建每个对象并将其推送到新数组中吗?

You could construct the array all at once using .map and using Object.fromEntries on an array of entries:您可以使用.map并在条目数组上使用Object.fromEntries一次构造所有数组:

 const user = [ { name: 'Bob' }, { name: 'Frank' } ]; const result = user.map(({ name }) => Object.fromEntries( ['key', 'value', 'text'].map(key => [key, name]) )); console.log(result);

If user might be undefined, you can alternate it with the empty array first:如果user可能未定义,您可以先将其与空数组交替使用:

const result = (user || []).map(...

There's no need to test user.length first, because if the length is 0, the result will remain the empty array, since there aren't any items to map over.没有必要先测试user.length ,因为如果长度为 0,结果将保持为空数组,因为没有任何项目可以映射。

When using .map() you should return the new element from the callback function.使用.map()您应该从回调函数中返回新元素。 If you don't return something, you should be using .forEach() .如果你不返回一些东西,你应该使用.forEach()

And you can use destructuring to avoid repeating u.name .您可以使用解构来避免重复u.name

result = user ? user.map(({name}) => ({ key: name, value: name, text: name })) : [];

尝试使用此语法在对象中创建新字段。

result["key"] = u.name

You can use @barmar's map() function or this reduce() function:您可以使用@barmar 的map()函数或这个reduce()函数:

const result = user.reduce((res, u) => {
    res.push({ key: u.name, value: u.name, text: u.name }); return res
}, [])

JavaScript has a Reduce Method. JavaScript 有一个 Reduce 方法。 You Should Use It. 你应该使用它。

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

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