0

Trying to convert an array of objects to a single object and the array I have is similar to the following;

const array = [{id: '1', name: 'First'}, {id: '2', name: 'Second'}];

Expected output:

{'first': 1, 'second': 2}

Additionally, I want to change the casing of all values to lower case. Can assume that there are no spaces in between for the values for names. And all the ids are numbers.

Performance-wise, is there a better approach than this?

const array = [{id: '1', name: 'First'}, {id: '2', name: 'Second'}];
console.log(array);
const result = array.reduce((accumulator, value) => {return {...accumulator, [value.name.toLowerCase()]: Number(value.id)}}, {});
console.log(result);

3 Answers 3

2

A simple for ... of (or similar) will likely be most performant as it has no overhead of function calls. For example:

const array = [
  {id: '1', name: 'First'},
  {id: '2', name: 'Second'}
];

let result = {};

for (o of array) {
  result[o.name.toLowerCase()] = parseInt(o.id);
}
console.log(result);

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

Comments

1

I think using a standard loop (for or while) would be the most efficient performance wise since it doesn't come with any additional stuff like map,reduce,sort do.

Comments

0

You could create entries and generate an object from it.

const
    array = [{ id: '1', name: 'First' }, { id: '2', name: 'Second' }],
    object = Object.fromEntries(array.map(({ id, name }) => [name.toLowerCase(), +id]));

console.log(object);

2 Comments

Can you explain why it is better than using a reducer, please?
it is just a compact approachwithout creating objects over an over.

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.