swagster
swagster

Reputation: 165

How to modify each JSON object javascript

I would like to modify each JSON value inside the cooldown object

{
  "cooldown":{
    "user": 1, // This
    "user2": 0 // This
  }
}

using a for statement in Javascript.

I've researched for hours and only could find a for inside [] blocks.

Edit

This is what I've tried:

for (var i in db["cooldown"]) {
  i = time.ms;
}

Upvotes: 3

Views: 2765

Answers (2)

Nageshwar Reddy Pandem
Nageshwar Reddy Pandem

Reputation: 1047

You can also use for..in method to loop through the object

var jsonObj = {
    "cooldown":{
    "user": 1,
    "user2": 0
  }
};


for(var key in jsonObj["cooldown"]){
    jsonObj["cooldown"][key] = "modified value";
}

console.log(jsonObj);

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122085

You can use Object.keys() to return array of keys and then use forEach() to loop that array and return each value.

var data = {
  "cooldown": {
    "user": 1, // This
    "user2": 0 // This
  }
}

Object.keys(data.cooldown).forEach(function(e) {
  console.log(data.cooldown[e]);
})

You can also use for...in loop

var data = {
  "cooldown": {
    "user": 1, // This
    "user2": 0 // This
  }
}

for (var k in data.cooldown) {
  console.log(data.cooldown[k]);
}

Upvotes: 2

Related Questions