Reputation: 17362
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?
Upvotes: 0
Views: 57
Reputation: 13158
You can use @barmar's map()
function or this reduce()
function:
const result = user.reduce((res, u) => {
res.push({ key: u.name, value: u.name, text: u.name }); return res
}, [])
JavaScript has a Reduce Method. You Should Use It.
Upvotes: -1
Reputation: 782693
When using .map()
you should return the new element from the callback function. If you don't return something, you should be using .forEach()
.
And you can use destructuring to avoid repeating u.name
.
result = user ? user.map(({name}) => ({ key: name, value: name, text: name })) : [];
Upvotes: 1
Reputation: 371193
You could construct the array all at once using .map
and using Object.fromEntries
on an array of entries:
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:
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.
Upvotes: 3
Reputation: 683
Try this syntax to create new fields in your object.
result["key"] = u.name
Upvotes: -1