7

I have one JSON Object like this :

var myObject = [    
{
    "Name" : "app1",
    "id" : "1",
    "groups" : [
        { "id" : "test1", 
          "name" : "test group 1", 
          "desc" : "this is a test group"
         },
        { "id" : "test2",
          "name" : "test group 2",
          "desc" : "this is another test group"
         }
    ]
},
{
    "Name" : "app2",
    "id" : "2",
    "groups" : [
        { "id" : "test3", 
          "name" : "test group 4", 
          "desc" : "this is a test group"
         },
        { "id" : "test4",
          "name" : "test group 4",
          "desc" : "this is another test group"
         }
    ]
},
 {
    "Name" : "app3",
    "id" : "3",
    "groups" : [
        { "id" : "test5", 
          "name" : "test group 5", 
          "desc" : "this is a test group"
         },
        { "id" : "test6",
          "name" : "test group 6",
          "desc" : "this is another test group"
         }
    ]
}

];

I have new value available of "name" for specific "id". How can I replace "name" of specific "id" inside any object ?

And how to count total number of groups among all objects ?

for example : replace name to "test grp45" for id = "test1"

Here is fiddle http://jsfiddle.net/qLTB7/21/

5
  • possible duplicate of Access / process (nested) objects, arrays or JSON Commented Jun 30, 2014 at 4:21
  • 3
    It's not a JSON object, it is just a javacsript object. Commented Jun 30, 2014 at 4:23
  • Yes. My mistake !. It's JS object. Thanks anyways. Commented Jun 30, 2014 at 4:37
  • @zerkms— *myObject * is an Array (which, granted, is a particular kind of Object). ;-) Commented Jun 30, 2014 at 4:50
  • In the outer object you have "Name", the inner objects you have "name", is that how it should be? Commented Jun 30, 2014 at 6:30

6 Answers 6

17

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Instead of break you could use return to make it more obvious that it stops there. Also, typeof object[x] == typeof {} is very inefficient (it creates a new object every time), use typeof object[x] == 'object'. Also should include a hasOwnProperty test, you don't want to check inherited enumerable properties.
@RobG - I wrote this up real quickly. I will add those changes.
1

Try this

function findAndReplace(object,keyvalue, name) {
    object.map(function (a) {
        if (a.groups[0].id == keyvalue) {
            a.groups[0].name = name
        }
    })
}

findAndReplace(myObject,"test1" ,"test grp45");

1 Comment

Thanks Manjesh. PitaJ suggested exactly same. Worked !
1

Maybe a more succinct sol'n

function changeName(objArray, objId, newName) {
    objArray.forEach(function(obj) {
        if (obj.id === objId) obj.Name = newName;
    });
}

Personally: if this were me, when creating these objects, I would create a new obj and key them by id.

 var myApps = {};
 myObject.forEach(function(o) {
     myApps[o.id] = o;
 });

=>
{
    "1": {
        "Name": "app1",
        "id": "1",
        "groups": [
            {
                "id": "test1",
                "name": "test group 1",
                "desc": "this is a test group"
            },
            {
                "id": "test2",
                "name": "test group 2",
                "desc": "this is another test group"
            }
        ]
    }
}

And then you could just do:

myApps['someId'].name = 'This is my new Name'

Check it out here: http://jsfiddle.net/qLTB7/40/

6 Comments

Hi Todd..Thank you for feedback..we can directly do the same with Object[0] , Object[1] right ?
That only works for objects in the first array, it doesn't recurse into the objects in the groups array. It also continues looping, even after a match has been found.
@vkaiz yes, we could do that in an iterative way, as you're describing. I thought you were just looking for a way to select an object by its ID, then change the name property.
@RobG, thanks for pointing out that the loop isn't broken until ALL objs are checked. On a different note, I didn't understand that "deep" name changing was needed.
@Todd—the OP says "How can I replace "name" of specific "id" inside any object", so I assumed it could be at any level. I might be wrong, only the OP knows. :-)
|
1

Here's a different approach using Array.prototype.some. It assumes that the Name property in the outer objects should be actually be name (note capitalisation).

function updateNameById(obj, id, value) {
  Object.keys(obj).some(function(key) {
    if (obj[key].id == id) {
      obj[key].name = value;
      return true;  // Stops looping
    }
      // Recurse over lower objects
      else if (obj[key].groups) {
      return updateNameById(obj[key].groups, id, value);
    }
  })
}

The advantage of some is that it stops as soon as the callback returns true.

Comments

0

I think this should work for you:-

var id = 'test1';
var newname = 'test grp45';
var numberOfGruops = 0;
myObject.forEach(function(app){
numberOfGruops += app.groups.length;    //Count all groups in this app
app.groups.forEach(function(group){
    if(group.id===id)
        group.name = newname;   // replace the name
});
});

Comments

0

it should be if (object["id"] == value) instead of if (object[x] == value) in 7th line of PitaJ answer, so whole function will look like:

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["id"] == value) { 
        object["name"] = replacevalue;
        // break; // uncomment to stop after first replacement
      }
    }
  }
}

if you leave object[x] - function will replace name also for objects with other keys values set to "test1", for example {"id": "xxx", "name": "test group 1", "desc": "test1"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.