Reputation: 319
Say I have this array:
var array = [{'ref1': {'Product': 'Car', 'color': 'Red'}}, {'ref2': {'product': 'velo', 'color': 'red'}}]
I want to add 'price': '8' to only 'ref1'
How can do this properly?
Alex.
Upvotes: 0
Views: 81
Reputation: 409
Find the index of the ref1 item, then assign the value to the Price parameter.
var array = [{'ref1': {'Product': 'Car', 'color': 'Red'}}, {'ref2': {'product': 'velo', 'color': 'red'}}];
var ref1 = array.filter(item => item == {'ref1': {'Product': 'Car', 'color': 'Red'}})[0];
var index = array.indexOf(ref1);
array[index]['Price'] = 8;
Upvotes: 0
Reputation: 15653
Here is a more dynamic code if you do not know for sure whether the object containing the "ref1" property is always at index 0:
const insert = (idProp, key, value) => {
var el = array.find(el => el.hasOwnProperty(idProp));
if (el) { el[idProp][key] = value }
}
then call it via
insert('ref1', 'Price', 8)
Upvotes: 2
Reputation: 6785
You could do something like:
var arr = [{'ref1': {'Product': 'Car', 'color': 'Red'}}, {'ref2': {'product': 'velo', 'color': 'red'}}];
console.log(arr);
arr[0]['ref1'].Price = 8;
console.log(arr);
Upvotes: 0
Reputation: 33024
This is how you do it: array[0]['ref1'].price = 8;
var array = [
{'ref1': {'Product': 'Car', 'color': 'Red'}}, {'ref2': {'product': 'velo', 'color': 'red'}}]
array[0]['ref1'].price = 8;
console.log(array)
Observation: ref1 has a property Product
while ref2 has a property product
in lowercase. This may cause you some problems latter.
Upvotes: 0