Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic operations on array of objects - JavaScript

Tags:

javascript

I have a JSON

const myJSON = [
    {
        name: 'compass',
        LocX: 35,
        LocY: 312
    },
    {
        name: 'another',
        LocX: 52,
        LocY: 32
    }
]

From the UI, if a user wants to add number 5 to one of the two properties, how should I handle this?

I am already doing

myJSON.map(x => x[userSelectedProperty] + 5)
// when user selected property is 'LocX', [40, 57]

but I want the full array with just the value updated.

[
    {
        name: 'compass',
        LocX: 40,
        LocY: 312
    },
    {
        name: 'another',
        LocX: 57,
        LocY: 32
    }
]

How do I do this?

like image 615
Testaccount Avatar asked Feb 15 '26 00:02

Testaccount


2 Answers

Simply iterate and update the object property using Array#forEcah method which is enough for this purpose.

const myJSON = [{
    name: 'compass',
    LocX: 35,
    LocY: 312
  },
  {
    name: 'another',
    LocX: 52,
    LocY: 32
  }
];

let userSelectedProperty = 'LocX';
myJSON.forEach(x => x[userSelectedProperty] += 5);

console.log(myJSON);

In case you want to create a new array then use Array#map method.

const myJSON = [{
    name: 'compass',
    LocX: 35,
    LocY: 312
  },
  {
    name: 'another',
    LocX: 52,
    LocY: 32
  }
];

let userSelectedProperty = 'LocX';
let res = myJSON.map(x => {
  // copy properties to a new object
  let y = Object.assign({}, x);
  y[userSelectedProperty] += 5;
  return y;
});

console.log(res);
like image 127
Pranav C Balan Avatar answered Feb 16 '26 12:02

Pranav C Balan


You could just use a .forEach loop on the array to update the property within it, rather than creating a new array.

const myJSON = [
    {
        name: 'compass',
        LocX: 35,
        LocY: 312
    },
    {
        name: 'another',
        LocX: 52,
        LocY: 32
    }
];
var userSelectedProperty = "LocX";
// Update the array.
myJSON.forEach(t => t[userSelectedProperty] += 5);

console.log(myJSON);
like image 21
Nisarg Shah Avatar answered Feb 16 '26 12:02

Nisarg Shah