3

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;
}
swagster
  • 165
  • 2
  • 10
  • please add some examples to illustrate you problem. – Nina Scholz Jul 04 '16 at 11:37
  • This is not clear. What is your current JSON and what is the expected outcome you want. – andybeli Jul 04 '16 at 11:37
  • 1
    I believe what you are actually asking is how to loop over each key/value pair in an object. If this is the case, perhaps this post will be helpful - http://stackoverflow.com/questions/7241878/for-in-loops-in-javascript-key-value-pairs – Lix Jul 04 '16 at 11:39
  • Your solution is close - but the `i` variable you are getting is not the value - it is the key. So you'd need to do something like `db["cooldown"][i]` – Lix Jul 04 '16 at 11:40
  • Ah okay, thank you again! :) – swagster Jul 04 '16 at 11:43
  • Those are not "JSONs". They are just plain old "fields", "properties", "key-value pairs", etc. – hippietrail Jul 04 '16 at 12:31

2 Answers2

2

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]);
}
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

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);