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?
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With