tags:

views:

37

answers:

2

I can create a Json object as here http://stackoverflow.com/questions/920930/how-to-create-json-by-javascript-for-loop great! and I have created on like bellow [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ]

Suppose I want to update name of the user with id 10 to "new name" what should i do?(i dont know the index is 1)

+1  A: 

Loop over your array of objects (because that's what it is), and check the "id" attribute of each object.

var list =  [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ];

for (var i=0;i<list.length;i++) {
  if (list[i].id == "10") {
    alert(i);
  };
};

You could then abstract this into some nice function.

function findIndexById(list, id) {
  for (var i=0;i<list.length;i++) {
    if (list[i].id == id) {
      return i;
    };
  };  

  return -1;
};

Then use it as follows:

var list =  [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ];
var index = findIndexById(list, "10");

if (index !== -1) {
  list[index].userName = "new username";
};
Matt
A: 

You can loop through the array and check the id property of the object in the current iteration. If it's 10, assign the new username to userName.

var json = [ { "id": "10", "userName": "kuttan" }, { "id": "11", "userName": "kunjan" } ],
    len = json.length,
    obj;

while(len--) {
  obj = json[len];
  if (obj.id == 10) {
      obj.userName = 'foobar';
  }
}

console.log(json); // outputs [{id:"10", userName:"foobar"}, {id:"11", userName:"kunjan"}]
Russ Cam