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".

4
  • 3
    Hint use console.log(), not alert() for debugging. Commented Jul 17, 2012 at 1:36
  • Not related to php or cakephp. Please only use tags that are relevant to the question. Commented Jul 17, 2012 at 1:37
  • PhpMyCoder-->oops sorry, im using javascript along with cakephp and php. my mistake. Commented Jul 17, 2012 at 1:41
  • Matt Ball--> alright, im gonna try.. im gonna post back here whatever the result is :) Commented Jul 17, 2012 at 1:42

4 Answers 4

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...
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks a lot nbrooks. Ive been wandering around so much moving away from the real problem. Thank you.
Actually, you shouldn't use for...in on arrays - link.
@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 here's another link that discusses the potential problems further: link
@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.
|
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);
    ...
}

1 Comment

can i mark two answers as correct? Thank you so much JohnnyHK.
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;   
}

2 Comments

thanks for the response Scott. I'll be needing them to be stored in an array for some other purposes :)
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.
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.

1 Comment

:) now that you mentioned it :) hahahah.. my mistake >.<

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.