coiso
coiso

Reputation: 7479

How may I change a JSON object in a specific location depending on another attribute?

{
  "employees": [
    { "firstName":"John" , "lastName":"Doe" }, 
    { "firstName":"Anna" , "lastName":"Smith" }, 
    { "firstName":"Peter" , "lastName":"Jones" }
  ]
}

How can we alter John's Last Name ? (without knowing it's Doe)

Upvotes: 2

Views: 183

Answers (2)

Ram
Ram

Reputation: 144719

You can use $.each utility function:

$.each(obj.employees, function(i, v){
   if (v.firstName === 'John') {  
       v.lastName = 'newValue'
       // return false
   }
})

http://jsfiddle.net/g7tzK/


You can also use the native for loop.

for (var i = 0; i < obj.employees.length; i++) {
   if (obj.employees[i].firstName === 'John') {
      obj.employees[i].lastName = 'newValue';
      return false;
   }
}

Upvotes: 3

kabaros
kabaros

Reputation: 5173

no need for jQuery:

for(var i in obj.employees)
{
    if(obj.employees[i].firstName == 'John')
    {
            obj.employees[i].lastName = "newValue";
    }
}

Upvotes: 1

Related Questions