0

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?

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What if user is undefined or empty array?
If it's an empty array, the result will be an empty array too - using .map on an empty array doesn't throw an error, it just doesn't go through any iterations.
Is there an advantage using two map() instead of doing it like @Barmar ?
I did it that way in order to be less repetitive. If you have a bunch of keys that you want for the new objects, you can just add them to the array inside the fromEntries callback, instead of having to list both the new key and the name again every time.
1

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 })) : [];

Comments

-1

Try this syntax to create new fields in your object.

result["key"] = u.name

6 Comments

result is an array, not an object.
result[index]["key"] = u.name than. It's an object array. This way you can assign key to something even if there is no key value in the object.
Why is this better than the way he's doing it with push()?
There's no result[index] until AFTER he pushes the object into it.
const user = [ { name: 'Bob' }, { name: 'Frank' } ]; for ( var i = 0; i < user.length; i++) result["key"] = user[i].name; console.log(result); It just works.
|
-1

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.

7 Comments

Just because you can use reduce() doesn't mean you should. If it's identical to map(), use map(). reduce() is appropriate if you want to collect conditionally.
Correct, reduce() provides more functionality than map() does. It's not limited to returning an array, either.
But IMHO it should only be used when the extra flexibility is needed. Other uses are often more confusing than helpful. It seems like some people here view almost every loop as requiring a demonstration of reduce's power.
That doesn't make this answer wrong, it provides a valid option with more potential while acknowledging your answer
Never said it was wrong, although I think that sometimes answers that use reduce when other solutions are simpler are just showing off their cleverness.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.