-3

I have a JSON object and need to update this object by searching the required node using a string 'locator' and then modify its value

e.g.

var jsonObj = {
  "School":{
    "Name":"ABC School",
    "City":"Chicago",
    "Zip":"53896"
  },
  "Students":[
    {"Name":"Student1",
     "Age": "12",
     "Gender":"Male"
    },
    {"Name":"Student2",
     "Age": "10",
     "Gender":"Female"
    },
    {"Name":"Student3",
     "Age": "15",
     "Gender":"Female"
    }
    ]
}

Action to be performed - Create a function to Search the object using locator string 'School.Name' and update value to 'ZYZ School' or Search the object using locator string 'School.Students.1.Age' and update value to '18'

function updateJSON(jsonObj, 'School.Name', 'ZYZ School' ){}
1

1 Answer 1

1

This should work

function updateJSON(jsonObj, locator, value) {
   var path = locator.split('.');
   if (!path.length) return;
   for (var i = 0; i < path.length - 1; ++i) {
        jsonObj = jsonObj[path[i]];
   }
   jsonObj[path[path.length - 1]] = value;  
}
Sign up to request clarification or add additional context in comments.

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.