gwydion93
gwydion93

Reputation: 1923

Adding a new element to an object in an array

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);
 });

Upvotes: 2

Views: 167

Answers (3)

Leonid Pyrlia
Leonid Pyrlia

Reputation: 1702

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}))

Upvotes: 0

hygull
hygull

Reputation: 8740

@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 } ]

Upvotes: 1

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28445

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);

Upvotes: 3

Related Questions