我们说我有这个对象:
{
categories: [
{ name: "My Category", products: [ { name: "My Product", price: 15 }] },
{ name: "Another", products: [ { name: "Movie", price: 25 }, { name: "Cartoon", price: 7.5 } ] },
{ name: "Lastly", subcategories: [
{ name: "Food", products: [ { name: "Avocado", price: 1.25} ] }
]
}
]
}
我希望能够通过函数调用更新此对象的价格,如下所示:
update(object, "categories/0/products/0",25)
// this would change first product in first category
这个答案Javascript: how to dynamically create nested objects using object names given by an array很好,但没有解决对象中有数组的情况。
可以接受的下划线。
注意:此答案Javascript: how to dynamically create nested objects INCLUDING ARRAYS using object names given by an array并没有删除它,因为我没有该表单中的数组引用(产品[1])
答案 0 :(得分:0)
您需要稍微修改链接答案中的功能
var object = {
categories: [
{ name: "My Category", products: [ { name: "My Product", price: 15 }] },
{ name: "Another", products: [ { name: "Movie", price: 25 }, { name: "Cartoon", price: 7.5 } ] },
{ name: "Lastly", subcategories: [
{ name: "Food", products: [ { name: "Avocado", price: 1.25} ] }
]
}
]
}
function update(obj, keyPath, value) {
keyPath = keyPath.split('/'); // split key path string
lastKeyIndex = keyPath.length-1;
for (var i = 0; i < lastKeyIndex; ++ i) {
key = keyPath[i];
// choose if nested object is array or hash based on if key is number
if (!(key in obj)) obj[key] = parseInt(key) !== parseInt(key) ? {}: []
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}
console.log(`Original price ${object.categories[0].products[0].price}`);
update(object, "categories/0/products/0/price",25)
console.log(`New price ${object.categories[0].products[0].price}`);