0

I have an array of items arr = ['1a', '2b', '3c', '4d'] and some id id = 'sasaas'. Now I want to make an array of objects such that elements of arr would be properties on objects inside new array, like

[
  {'id1' : id, 'id2': '1a'}
  {'id1' : id, 'id2': '2b'}
  {'id1' : id, 'id2': '3c'}
  {'id1' : id, 'id2': '4c'}
]

I tried this

let arr = ['1a', '2b', '3c', '4d'];
let id = 'sasaas';
let c = arr.map(i => {'id1': id, 'id2': i})

but it didn't work. I don't what I'm doing wrong here, any Idea?

kapil sarwat
  • 97
  • 1
  • 8
  • Add `()` (parentheses) around those braces in the lambda – Chase May 05 '21 at 08:05
  • As a side note and general advice - as a programmer, never use the words "it doesn't work" - explain exactly what happens, the phrase "doesn't work" serves no purpose other than to waste time. – Chase May 05 '21 at 08:06
  • `arr.map(i => {'id1': id, 'id2': i})` -> `arr.map(i => ({'id1': id, 'id2': i}))` or `arr.map(i => { return {'id1': id, 'id2': i}; })` – VLAZ May 05 '21 at 08:06

1 Answers1

3

This will give you the array you desire.

let arr = ['1a', '2b', '3c', '4d'];
let id = 'sasaas';
let c = []
arr.forEach(i => c.push({'id1': id, 'id2': i}))

Use forEach instead of .map as @Chase said it has some side effects

M.Hassan Nasir
  • 851
  • 2
  • 13
  • Please refrain from suggesting the use of `.map` in this way. It is generally considered bad practice to use `.map` for side effects. Side effects is the opposite of functional programming. – Chase May 05 '21 at 08:06
  • Please don't use `.map()` for simple iteration. Use `forEach()` or an actual loop. – VLAZ May 05 '21 at 08:07