2

Lets say I have and array made up of objects:

var points = [
  { id: 1, a: 0, b: 3 },
  { id: 2, a: 4, b: -1 },
  { id: 3, a: -1, b: 5 },
  { id: 4, a: 41, b: 2 },
  { id: 5, a: 69, b: 3 },
]

I want to iterate through each item and add a + b to get a new item d. I then want to add d within each object in the array to get a new value. When I try the below, it just adds 5 extra objects rather than appending the new element (key=value, ex: d: 3) to each individual object. What am I doing wrong here?

 points.forEach((item) => {
   var d = Math.abs(item.x) + Math.abs(item.y);
   console.log(d);
   points.item.push('d: ' + d);
 });
1
  • Your objects look to have a and b properties, not x and y properties? Commented Jun 15, 2018 at 2:50

3 Answers 3

3

Try following

var points = [{ id: 1, a: 0, b: 3 },{ id: 2, a: 4, b: -1 },{ id: 3, a: -1, b: 5 },{ id: 4, a: 41, b: 2 },{ id: 5, a: 69, b: 3 }];

points.forEach(o => o.d = Math.abs(o.a) + Math.abs(o.b));
console.log(points);

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

Comments

1

@jcbridwe, you can use assign() method on Object to add missing property from source object to target object.

Please have a look at the below code.

Try the below code online at http://rextester.com/EPHYV10615.

var points = [
  { id: 1, a: 0, b: 3 },
  { id: 2, a: 4, b: -1 },
  { id: 3, a: -1, b: 5 },
  { id: 4, a: 41, b: 2 },
  { id: 5, a: 69, b: 3 },
]

for(var index in points){
    var a = points[index].a;
    var b = points[index].b;

    Object.assign(points[index], {d: a+b});
}

console.log(points);

» Output

[ { id: 1, a: 0, b: 3, d: 3 },
  { id: 2, a: 4, b: -1, d: 3 },
  { id: 3, a: -1, b: 5, d: 4 },
  { id: 4, a: 41, b: 2, d: 43 },
  { id: 5, a: 69, b: 3, d: 72 } ]

2 Comments

I went with this solution as it added the most relevance to changes I made to the code.
Thanks @gwydion93.
0

Mutable approach:

points.forEach(o => o.d = o.a + o.b);

Immutable approach:

const newPoints = points.map(o => Object.assign({}, o, {d: o.a + o.b}))

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.