JSON Object array inside array find and replace in javascript

后端 未结 6 1365
长发绾君心
长发绾君心 2020-12-18 01:21

I have one JSON Object like this :

var myObject = [    
{
    \"Name\" : \"app1\",
    \"id\" : \"1\",
    \"groups\" : [
        { \"id\" : \"test1\", 
             


        
6条回答
  •  执笔经年
    2020-12-18 02:05

    The following function will search through an object and all of its child objects/arrays, and replace the key with the new value. It will apply globally, so it won't stop after the first replacement. Uncomment the commented line to make it that way.

    function findAndReplace(object, value, replacevalue) {
      for (var x in object) {
        if (object.hasOwnProperty(x)) {
          if (typeof object[x] == 'object') {
            findAndReplace(object[x], value, replacevalue);
          }
          if (object[x] == value) { 
            object["name"] = replacevalue;
            // break; // uncomment to stop after first replacement
          }
        }
      }
    }
    

    Working jsfiddle: http://jsfiddle.net/qLTB7/28/

提交回复
热议问题