JSON Object array inside array find and replace in javascript

后端 未结 6 1374
长发绾君心
长发绾君心 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:15

    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.

提交回复
热议问题