1
\$\begingroup\$

Is there a better way to do this?

const data = [{id: 1, name: 'item1'}, {id: 2, name: 'item2'}]
const a = []
data.forEach(x => { a[x.id] = x.name })
return a // ['1': 'item1', '2': 'item2']
\$\endgroup\$
3
  • \$\begingroup\$ Include the language as a tag and a little bit more info like what do you use this chunk of code for.. \$\endgroup\$ Commented Sep 16, 2016 at 18:33
  • \$\begingroup\$ ['1': 'item1', '2': 'item2'] isn't a valid array. Did you mean ['1', 'item1', '2', 'item2'] or something else? \$\endgroup\$ Commented Sep 18, 2016 at 0:31
  • \$\begingroup\$ The answer of Joseph resume it all \$\endgroup\$ Commented Sep 20, 2016 at 13:36

1 Answer 1

4
\$\begingroup\$

Yes. Use array.reduce and use an object.

const a = data.reduce((items, item) => (items[item.id] = item.name, items), {});

// a = {1:{...}, 2: {...};

You can still use the bracket notation to access the items, i.e. a[id].

A problem with using IDs as array indices is that you introduce gaps in the array. You also get a false array length. Take the following example:

const a = [];
a[999] = {/* User data */};
a.length // 1000;

You only added a single item, with id "999" but now the array reports 1000 in length. Items 0 to 998 are actually empty.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks a lot. I was not sure the solution was the reduce. You confirmed it with a perfect example. I know about the length but the part of the code that deal with it is quit big. It's something I need to improve in time. :thumbsup: \$\endgroup\$ Commented Sep 16, 2016 at 20:07

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.