-1

So a two part question, because I can't solve the first problem, and the hacky work around isn't seeming to work either.

I have a JSON object, and within that object is nested object. I want to manipulate something within a deep layer array.

So to start with, I need to learn how to iterate over keys in an object, but I can't see how you do it.

Say I have an object with objects within it, how do I iterate over these? If it were an array I would do

for (i = 0; i < arrayLength; i++)
   {console.log(array[i])}

But, because they're words, I can't just i++, so I made an array of the words, then wanted to do the same as above, but

for (i = 0; i < arrayLength; i++)
   {console.log(jsonObject.array[i]}

, but this isnt seeming to work, I just get undefined returned.

Apologies for the poor explaination.

  • 2
    what does your object look like? – Alex Jan 05 '17 at 22:44
  • https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion\?champData\=skins\&api_key\=RGAPI-a9b9e9ab-943d-4d59-b041-c22663d53b4b to be specific, I've been looking at both of those threads for like 2 hours now, the later link returns single characters in my terminal, the first just looks likeJquery? – Sam Stone Jan 05 '17 at 22:46
  • No question is "stupid"... "A wise man can learn more from a foolish question than a fool can learn from a wise answer." - Bruce Lee – BrunoLM Jan 05 '17 at 22:49
  • Yeah, but some questions can be answered with a simple google, and thats a waste of everyones time, like I'm sure this is – Sam Stone Jan 05 '17 at 22:49
  • 1
    Well if you actually posted what the JSON looked like, people could help you instead of guessing. Put the JSON in your question. – epascarello Jan 05 '17 at 22:51
  • @SamStone as you can see in the duplicated question, at least 1300+ SO users don't think this is foolish. There is also people from outside summing 511850+ views. :) – BrunoLM Jan 05 '17 at 22:57

3 Answers3

0

There is a method to get the keys and then you can iterate with those.

var keys =    Object.keys(obj);

for(i = 0 ; i < keys.length; i++){
   var result = obj[keys[i]];
   console.log(result);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

applecrusher
  • 5,508
  • 5
  • 39
  • 89
0

You need to use a 'for..in' loop, or, even better, Object.keys() handles this well.

Object.keys() documentation here.

for (var i in myObject) { console.log[i] };
jmoneygram
  • 129
  • 1
  • 9
0

You iterate using for (key in obj) {...} syntax.

As in:

var t = document.getElementById('myTextField');
var obj = {name:'John',last:'Doe'};
var result = '';
for (key in obj) {
        result += key + '=' + obj[key] + ',';
}
danim
  • 1
  • 2