从字符串路径动态更新 JavaScript 对象 [英] Dynamically updating a JavaScript object from a string path
问题描述
我试图弄清楚是否可以使用字符串作为路径来更新 JavaScript 对象.
Im trying to figure out if its possible to update a JavaScript object, using a string as the path.
在下面的示例中,我试图弄清楚如何使用store>book>0>price
作为我的路径.
In the example below, I'm trying to figure out how I can update the first books price using
store>book>0>price
as my path.
我知道我可以通过编写 data['store']['book'][0]['price']
来访问它,但我需要能够动态地做到这一点.我尝试了一些东西,但没有运气.有什么想法吗?
I know I can access this by writing data['store']['book'][0]['price']
but I need to be able to do this dynamically. Ive tried a few things but had no luck. Any Ideas?
这需要适用于任何深度,而不是固定深度
数据:
var data = {
"store": {
"book": [
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
var path = "store>book>0>price"
功能:
function updateObject(object, path, data) {
var pathArray = path.split(">");
// Some code here
}
updateObject(data, path, "10.00");
<小时>
更新
正如 felix 指出的,答案可以在这里找到.JavaScript 对象的动态深度设置
As felix pointed out the answer can be found here. Dynamic deep setting for a JavaScript object
这是我的场景的一个工作示例http://jsfiddle.net/blowsie/Sq8j3/9/
Here is a working example for my scenario http://jsfiddle.net/blowsie/Sq8j3/9/
推荐答案
function updateObject(object, newValue, path){
var stack = path.split('>');
while(stack.length>1){
object = object[stack.shift()];
}
object[stack.shift()] = newValue;
}
这篇关于从字符串路径动态更新 JavaScript 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!