0

I have an object in my javascript which looks like this:

{"data":[{"t":{
                "level":"35",
                "longtitude":"121.050321666667",
                "latitude":"14.6215366666667",
                "color":"#040098"}},
         {"t":{
                "level":"31",
                "longtitude":"121.050316666667",
                "latitude":"14.621545",
                "color":"#040098"}},
         {"t":{
                "level":"29",
                "longtitude":"121.050323333333",
                "latitude":"14.62153",
                "color":"#040098"}},
//  .....

What I would like to do is to iterate thru the contents of my object so that I will be able to push them to their respective arrays independently. I have an array for longitude, latitude, color and level.

So I have tried the following:

var size = 0, key;
for (key in result) {
    if (result.hasOwnProperty(key)) size++;
    alert(result.data[size]);
}

-->But this only alerts me "[object Object]"

success: function(result){
    var size = 0, key;
    for (key in result) {
        for(var attr in key){
            alert(attr['latitude']);
        }
    }
}

-->This gives me Undefined result[key]

I have checked that the size of my object is only 1 thru these codes

var size = 0, key;
for (key in result) {
    if (result.hasOwnProperty(key)) size++;
}
alert(size);        

I believe that only "data" is being read. And others that are inside "data" are disregarded.

I have read this, this, enter link description here, and this but they sall seem to deal with a different structure of objects. Thanks for the help in advanced.

UPDATE Using the console.log(), I have confirmed, if im not mistaken that only the first attribute is being fetched

t
    Object { level="35", longtitude="121.0508", latitude="14.6204083333333", more...}
color       "#040098"
latitude    "14.6204083333333"
level       "35"
longtitude  "121.0508"

I tried this

for (key in result) {
            if (result.hasOwnProperty(key)) size++;
            console.log(result.data[size]['level']);
        }

--> but it says undefined

based on the structure of my object which is

data:[{"t":{'others'},'others'...]

How am I to read everything inside "data"? Each "data" has "t".

Community
  • 1
  • 1
Charmie
  • 2,468
  • 7
  • 33
  • 47

4 Answers4

1

Update: Using the for...in construct for iterating over arrays isn't recommended. The alternative is a regular for loop (each method of course having their respective advantages):

for(var i=0; i<results.data.length; i++){
    alert(results.data[i]['t']['latitude']);
    // etc...
}


Be careful with the structure of your JSON. Also note that the javascript foreach loop iterates over keys/indices -- not values. See demo: http://jsfiddle.net/g76tN/
success: function(result){
    var latitudes = [];
    // and so on...

    for (var idx in result.data ) {
        if( result.data.hasOwnProperty(idx) ){
            alert( result.data[idx]['t']['latitude'] );

            // So you would do something like this:
            latitudes.push ( result.data[idx]['t']['latitude'] );
            // and so on...
        }
    }
}​

Note for collecting properties of objects in an array, jQuery $.map() -- or native js array map for that matter -- is a neat, useful alternative.

var latitudes = $.map( result.data, function(n){
    return n['t']['latitude'];
});
// and so on...
nbrooks
  • 18,126
  • 5
  • 54
  • 66
  • Thanks a lot nbrooks. Ive been wandering around so much moving away from the real problem. Thank you. – Charmie Jul 17 '12 at 01:57
  • Actually, you shouldn't use `for...in` on arrays - [link](http://stackoverflow.com/questions/1885317/strange-behavior-in-javascript-enhanced-for-in-loop/1885365#1885365). – JohnnyHK Jul 17 '12 at 02:02
  • @johnny on the contrary, I think that this is a very legitimate (and fundamental) way of iterating over arrays. I added a hasOwnProperty check for safety's-sake though. – nbrooks Jul 17 '12 at 02:15
  • @nbrooks here's another link that discusses the potential problems further: [link](http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays) – JohnnyHK Jul 17 '12 at 02:25
  • @johnny The fact that it only iterates over set indices is what makes it really useful for retrieving values from an array as requested in the question -- it's more efficient than looping through index by index from the beginning and checking if the value is `undefined` or otherwise alerting it. As for the issue with `Array.prototype`, using `hasOwnProperty` avoids that -- though again this kind of iteration is more fundamental than extending `Array.prototype`, and less likely to become problematic and cause clashes with external code etc. – nbrooks Jul 17 '12 at 02:33
  • @johnny [link](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml?showone=Modifying_prototypes_of_builtin_objects#Modifying_prototypes_of_builtin_objects) Sorry, this couldn't fit...but anyway extending Array.prototype is not recommended in the first place – nbrooks Jul 17 '12 at 02:33
  • 2
    @nbrooks fair enough; I guess it's more right to say that if you use `for...in` on arrays, you need to be aware of some potentially non-obvious behavior. Good discussion, thanks. – JohnnyHK Jul 17 '12 at 02:39
1

Assuming result is your object, this should just be a matter of iterating over your data array:

for (var i = 0; i < result.data.length; ++i) {
    console.log(result.data[i].t.latitude);
    ...
}
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
1

It's not hard to do, as shown below. But why would you want to take useful objects like your t's and turn them into such arrays?

var levels = [], longitudes= [], latitudes = [], colors = [];
var result = {"data":[{"t":{
            "level":"35",
            "longtitude":"121.050321666667",
            "latitude":"14.6215366666667",
            "color":"#040098"}},
     {"t":{
            "level":"31",
            "longtitude":"121.050316666667",
            "latitude":"14.621545",
            "color":"#040098"}},
     {"t":{
            "level":"29",
            "longtitude":"121.050323333333",
            "latitude":"14.62153",
            "color":"#040098"}}
]};

var data = result.data;
var i, len, t;

for (i = 0, len = data.length; i < len; i++) {
    t = data[length].t;
    levels[i] = t.level;
    longitudes[i] = t.longtitude;
    latitudes[i] = t.latitude;
    colors[i] = t.color;   
}
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
  • thanks for the response Scott. I'll be needing them to be stored in an array for some other purposes :) – Charmie Jul 17 '12 at 02:00
  • There are plenty or reasonable scenarios where you would need such arrays, but the original objects seem much more useful, although the entire `results` object seems bloated. – Scott Sauyet Jul 17 '12 at 02:07
0

See http://jsfiddle.net/VGmee/, which keeps the hasOWnProperty (which is important), and your misspelling of "longitude", which is not.

var data = input.data,
    result = {level: [], longtitude: [], latitude: [], color: []};

for (var i = 0, n = data.length; i < n; i += 1) {
    var info = data[i].t;
    for (var property in info) {
        if (info.hasOwnProperty(property)) {
            result[property].push(info[property]);
        }
    }
}

console.log(result.level);
console.log(result.latitude);
console.log(result.longtitude);
console.log(result.color);

This requires the result arrays to actually have the properties in your input array, but you can add error handling as desired.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232