Find the value for the given key in JSON and change the value using javascript

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

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

Function input is a key tree. For example, myData-address-details-prevhouse

When I pass this key with a new value, say Texas, the prevailing value will be changed to the new value that I am sending.

and the new JSON will be

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

Here is what I wrote so far

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

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

I know that we can access the object using myData [tree [0]] [tree [1]] [tree [2]], but somehow we cannot get it dynamic from parsing.

, .

.

0
4

:

    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; .

+3

, JSON - JS. , , , , . , . , .

psuedo- :

obj = data;
for (key in keys) {
  obj = obj[key]
}
+1

- :

function update(node, path, value) {
  path = path.split('-');
  do {
    node = node[path.splice(0, 1)];
  } while(path.length > 1);
  node[path[0]] = value;
}
+1

Given what myDatais an object, I think you should use myData[tree[1]][tree[2]][tree[3]]and throw away the first element in the array.

Something like this should work recursively (unchecked)

function updateValue(obj, key, value)
{
   var keys = key.split('-');
   updateObjectValue(obj, keys.shift(), value);
}

function updateObjectValue(obj, keyArray, value)
{
     if (keyArray.length == 1) {
         obj[keyArray[0]] = value;
     }
     else if (keyArray.length > 1) {
         updateObject(obj[keyArray[0]], keyArray.shift(), value);
     }
}
0
source

All Articles