Reputation: 278
I have a JSONArray with JSONObjects , i want the find a JSONObject based on condition and update it . Consider my json as below
ManagerArr = [
{
name : "Ram",
employees: ["Shyam","bhavya"]
},
{
name: "Ramya",
employees: ["Keerthi", "suresh"]
}
I want to update above array when i get new list of employees, i have to find the json object by validating manager name and then add them to employees array. i can iterate on whole jsonArray for every new employee, but do we have any in-built method to do so. i don't want to iterate the whole array every time, can i get the index of JSONObject in JSONArray by any chance
Upvotes: 0
Views: 49
Reputation: 45
I may be wrong, but unfortunately, if you keep the objects representing each manager inside of an array, I don't believe you can achieve your desired outcome without looping through every manager (even if there is a built-in function that may make it seem like you're not looping, it will probably still be doing a loop under the hood).
However, if you're able to modify the data structure a bit, it can be done quite easily!
I would implement it in the following way:
managers = {
"Ram": {
employees: ["Shyam", "bhavya"]
},
"Ramya": {
employees: ["Keerthi", "suresh"]
}
}
If you do it this way, you can easily modify the employee information of each manager without having to loop through existing managers.
For example:
manager = "Ram";
newEmployees = ["John", "Steven", "Katie"]
// manager doesn't yet exist
if (!managers[manager]) {
// create new manager and their employee info
managers[manager] = { employees: newEmployees }
}
// manager already exists
else {
// get existing employees and update them
existingEmployees = managers[manager].employees;
existingEmployees = [...existingEmployees, ...newEmployees];
}
I hope this helps!
Upvotes: 0