0

I can't add a key value pair to my array objects:

 const arr = [{'a' :1, 'b':2},{'a':2, 'b':4}]
 arr.map( item => {item.price = 1
 document.getElementById("body").innerHTML += 'a : '+ item.price + ' ' });
   

I want arr to be :

{'a' :1, 'b':2, 'price' : 1},{'a':2, 'b':4, 'price' : 1}
4
  • 1
    getElementById("body") ?? Commented May 5, 2021 at 19:59
  • Why are you using document if you only want to edit the array? Commented May 5, 2021 at 20:02
  • I was trying to display the result, It's not the problem, consider it a console.log.. Commented May 5, 2021 at 20:03
  • map needs to return a new item. item.price = 1 will amend the incoming item, and then return 1, making the array [1,1] Commented May 5, 2021 at 20:04

1 Answer 1

4

The map function doesn't modify the array you do it to, it returns a new modified array. So you must assign the output to a variable. I would suggest reading a bit more how mapping arrays works on the MDN Docs.

Here's how I would implement what you're looking for:

const arr = [{'a' :1, 'b':2},{'a':2, 'b':4}];
const newarr = arr.map( item => ({ ...item, price: 1 }) )
Sign up to request clarification or add additional context in comments.

Comments

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.