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;
}
6
  • please add some examples to illustrate you problem. Commented Jul 4, 2016 at 11:37
  • This is not clear. What is your current JSON and what is the expected outcome you want. Commented Jul 4, 2016 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 - stackoverflow.com/questions/7241878/… Commented Jul 4, 2016 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] Commented Jul 4, 2016 at 11:40
  • Ah okay, thank you again! :) Commented Jul 4, 2016 at 11:43

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

8 Comments

Does this require JQuery?
So I'm trying to create an if statement to check if a value is equal to zero, and it's completely ignoring that. Would you like me to post my code in an edit or ask a new question?
I added a comment inside the fiddle to explain what I want to do.
Its never zero its -1 and 5.
So change the if statement to be == -1?
|
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.