在JSON中查找给定键的值,并使用javascript更改该值 [英] Look for a value for a given key in JSON and change the value using javascript

查看:89
本文介绍了在JSON中查找给定键的值,并使用javascript更改该值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个可以根据键查找值并将该值替换为另一个值的函数。密钥是来自JSON起始节点的树。这是一个例子。

I am looking to write a function which can look up a value based on a key and replace that value with another. The key is a tree from the start node of JSON. Here is the example.

var myData = {
    name : 'Dan',
    address: {
        city : 'Santa Clara',
                details : {
                   'prevhouse' : ''
                }
    }
}

该函数的输入是一个关键树。例如,myData-address-details-prevhouse

Input to the function is a key tree. For eg, myData-address-details-prevhouse

当我使用新值传递此键时,例如'Texas',prevhouse值将更改为新值我发送。

When I pass this key with a new value, say 'Texas', the prevhouse value will get changed to the new value I am sending.

和新的JSON将是

var myData = {
    name : 'Dan',
    address: {
        city : 'Santa Clara',
                details : {
                   'prevhouse' : 'Texas'
                }
    }
}

这是我到目前为止所写的内容/ p>

Here is what I wrote so far

var tree = key.split("-");

现在树变量包含[myData,address,details,prevhouse ]

now the tree variable contains ["myData","address", "details","prevhouse"]

我知道我们可以使用myData [tree [0]] [tree [1]] [tree [2]]访问该对象,但不知何故不能从解析后的值中获取动态。

I know that we can access the object using myData[tree[0]][tree[1]][tree[2]], but somehow not able to get it dynamic from parsed value.

我们如何动态生成它,因为直到运行时才知道深度的长度。

how do we generate this dynamically since the length of the depth is not known till runtime.

希望得到帮助。

推荐答案

尝试使用此代码:

    var myData = {
        name: 'Dan',
        address: {
            city: 'Santa Clara',
            details: {
                prevhouse: ''
            }
        }
    };


    function setAttribute(obj, key, value) {
        var i = 1,
            attrs = key.split('-'),
            max = attrs.length - 1;

        for (; i < max; i++) {
            attr = attrs[i];
            obj = obj[attr];
        }

        obj[attrs[max]] = value;
        console.log('myData=', myData);

    }

    setAttribute(myData, "myData-address-details-prevhouse", "Texas");

这里一个有效的jsfiddle演示;看到控制台的结果

here a working jsfiddle demo; see the console for the result

这篇关于在JSON中查找给定键的值,并使用javascript更改该值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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