简体   繁体   中英

How do I get the main property of a javascript object?

I'm working on a site that pulls data from a third party site. My PHP pulls the data and responds with a really nice JSON object. I then use $.each to iterate over the object and sort through the data which works great. The problem is I dont know how to pull the main property.

Example JSON response:

{
    "1234": {
        "all_sales": {"11/12/2012":"1211.33","11/13/2012":"2012.45"},
        "sales_total":"323.78",
        "store_number":"1234",
    },
     "5678": {
        "all_sales": {"11/12/2012":"1211.33","11/13/2012":"2012.45"},
        "sales_total":"323.78",
        "store_number":"5678",
    },

}

1234 and 5678 are store numbers. What I want is to not need the store_number property and just know thats what it is. In PHP it would be something like:

for ($data as $store_number => $store_data){
    //do whatever
}

Im doing this for all sorts of reasons, but mainly so I can simply call data.1234 or build an array of sales for like a top 10. For now the store_number property lets me do this but its extra data that isn't needed.

I think you want to use the first argument of the $.each callback function:

var a = { "1234": { ... }, "5678": { ... } };

$.each(a, function(main, val) {
    console.log(main); // prints "1234" and "5678"
});

for x in loops are the right tool for the job here. I like jQuery, but don't whip out the JQ-hammer when JavaScript has it covered.

var myObj = {
    "1234": {
        "all_sales": {"11/12/2012":"1211.33","11/13/2012":"2012.45"},
        "sales_total":"323.78",
        "store_number":"1234",
    },
     "5678": {
        "all_sales": {"11/12/2012":"1211.33","11/13/2012":"2012.45"},
        "sales_total":"323.78",
        "store_number":"5678",
    },

}

for (var x in myObj) {
    alert('property:' + x);
    alert('property.sales_total:' + myObj[x].sales_total); 
}

If I understand correctly, you want an array with the values '1234', '5678', etc.:

myArray=$.map(myJSON,function(value,key){return key;});

[Edit] On second thoughts, this might be closer to what you're after:

myArray=$.map(myJSON,function(value,key){
// do whatever
});

And as @Ian said in the comment, you might want to group all your processing in a single loop (either $.each or $.map as in my example).

for (var key in object) {
    console.log(key);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM