Kuttan Sujith
Kuttan Sujith

Reputation: 7979

Creating and Updating JSON

I can create a Json object as here How to create json by javascript for loop? great! and I have created one like below

[
    {
        "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)

Upvotes: 0

Views: 1595

Answers (2)

Russ Cam
Russ Cam

Reputation: 125528

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"}]

Upvotes: 0

Matt
Matt

Reputation: 75327

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";
};

Upvotes: 1

Related Questions