gpt4 book ai didi

javascript - 从字符串路径动态更新 JavaScript 对象

转载 作者:数据小太阳 更新时间:2023-10-29 05:41:23 25 4
gpt4 key购买 nike

<分区>

我试图弄清楚是否可以使用字符串作为路径来更新 JavaScript 对象。

在下面的示例中,我试图找出如何使用更新第一本书的价格store>book>0>price 作为我的路径。

我知道我可以通过编写 data['store']['book'][0]['price'] 来访问它,但我需要能够动态地执行此操作。我尝试了几件事,但没有运气。有什么想法吗?

这需要适用于任何深度,而不是固定深度


数据:

 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 指出的那样,答案可以在这里找到。 Dynamic deep setting for a JavaScript object

这是我的场景的一个工作示例 http://jsfiddle.net/blowsie/Sq8j3/9/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com