从字符串路径动态更新JavaScript对象 [英] Dynamically updating a JavaScript object from a string path

查看:161
本文介绍了从字符串路径动态更新JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚是否可以使用字符串作为路径来更新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?

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

This needs to work for any depth , not a fixed depth

数据:

 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");






更新

正如费利克斯指出的那样,答案可以在这里找到。
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆