Let’s say I have this object:
JavaScript
x
11
11
1
{
2
categories: [
3
{ name: "My Category", products: [ { name: "My Product", price: 15 }] },
4
{ name: "Another", products: [ { name: "Movie", price: 25 }, { name: "Cartoon", price: 7.5 } ] },
5
{ name: "Lastly", subcategories: [
6
{ name: "Food", products: [ { name: "Avocado", price: 1.25} ] }
7
]
8
}
9
]
10
}
11
I’d like to be able to update the price in this object through a function call as follows:
JavaScript
1
3
1
update(object, "categories/0/products/0",25)
2
// this would change first product in first category
3
This answer Javascript: how to dynamically create nested objects using object names given by an array is good but does not address the case when there are arrays in the object.
Underscore acceptable.
Note: this answer Javascript: how to dynamically create nested objects INCLUDING ARRAYS using object names given by an array does not cut it because I don’t have array references in that form (products[1])
Advertisement
Answer
You need to slightly modify function from the linked answer
JavaScript
1
27
27
1
var object = {
2
categories: [
3
{ name: "My Category", products: [ { name: "My Product", price: 15 }] },
4
{ name: "Another", products: [ { name: "Movie", price: 25 }, { name: "Cartoon", price: 7.5 } ] },
5
{ name: "Lastly", subcategories: [
6
{ name: "Food", products: [ { name: "Avocado", price: 1.25} ] }
7
]
8
}
9
]
10
}
11
12
function update(obj, keyPath, value) {
13
keyPath = keyPath.split('/'); // split key path string
14
lastKeyIndex = keyPath.length-1;
15
for (var i = 0; i < lastKeyIndex; ++ i) {
16
key = keyPath[i];
17
18
// choose if nested object is array or hash based on if key is number
19
if (!(key in obj)) obj[key] = parseInt(key) !== parseInt(key) ? {}: []
20
obj = obj[key];
21
}
22
obj[keyPath[lastKeyIndex]] = value;
23
}
24
25
console.log(`Original price ${object.categories[0].products[0].price}`);
26
update(object, "categories/0/products/0/price",25)
27
console.log(`New price ${object.categories[0].products[0].price}`);