2

Possible Duplicate:
Getting JavaScript object key list
How to iterate json data in jquery

I have a json like this one:

var myJSONObject = {
                    "flowers": [
                        {"id":"1","name":"Red Flower","url":"flower_1.png"},
                        {"id":"2","name":"Purple Flower","url":"flower_2.png"},
                        {"id":"3","name":"Yellow Flower","url":"flower_3.png"},
                        {"id":"4","name":"Violet Flower","url":"flower_4.png"},
                        {"id":"5","name":"Purple Flower","url":"flower_5.png"}
                    ],
                    "bouquet": [
                        {"first":[1,2,3,4,5,6]},
                        {"second":[1,2,3,4,5,6]},
                        {"third":[1,2,3,4,5,6]}
                    ]
            };

Now my questin is how can I pull only the names of members of "bouquet"...into array. Something that will look like that : ["first","second","third"]?

Community
  • 1
  • 1
BorisD
  • 2,231
  • 5
  • 25
  • 35
  • This is not related to JSON, which is a data exchange format, but simply to JavaScript objects. – Felix Kling Jan 03 '12 at 16:46
  • @FelixKling and John, this question is distinct from the others. In case you didn't notice: The named keys are unknown. A double loop is required to solve this. – Rob W Jan 03 '12 at 16:50
  • @Rob W: don't think so: `for (var p in myJSONObject.bouquet) ...` – just somebody Jan 03 '12 at 16:53
  • @RobW: I see what you mean. Still, I'd assume (I'm an optimist) that one knows how to iterate over an array. – Felix Kling Jan 03 '12 at 17:01
  • @justsomebody Your suggestion returns a list of `[object Object]`s, while the OP wants `["first",...]`. These "duplicates" are dealing with lists of the kind `[a, b, c]`, while this question is about `[{a:..}, {b:..}, {c:..}]`. – Rob W Jan 03 '12 at 17:01

3 Answers3

3

In recent Firefox browsers, the following can be used (so-called Array-comprehensions):

var list = [Object.keys(i)[0] for each (i in myJSONObject.bouquet)];

If Object.keys is supported, use:

var list = [];                        // Create list
for (var i=0; i<myJSONObject.bouquet.length; i++) {
    var keys = Object.keys(myJSONObject.bouquet[i]); //List keys
    list.push(keys[0]);               // Store first named key
}

In other browsers, you can use:

var list = [];                        // Create list
for (var i=0; i<myJSONObject.bouquet.length; i++) {
    var key = myJSONObject.bouquet[i];
    for (var j in key) {              // Get the first named key
        list.push(j);                 // Store named key
        break;                        // <--- First named key, so break loop
    }
}
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Is there an es:harmony version of array comprehensions – Raynos Jan 05 '12 at 17:57
  • [Array comprehensions](http://wiki.ecmascript.org/doku.php?id=harmony:array_comprehensions) are listed at the [proposals](http://wiki.ecmascript.org/doku.php?id=harmony:proposals) page. – Rob W Jan 05 '12 at 18:05
1
for(var i=0; i< myJSONObject["bouquet"].length; i++)
{
  var o = myJSONObject["bouquet"][i];
  document.write(Object.keys(o) + "<br>");
}

output: first second third

JSFiddle for confirmation

NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • Already found the answer...but thank you all! – BorisD Jan 03 '12 at 17:20
  • @BorisD Beware of the code in this answer. `Object.keys` returns an array. If you're going to create a list in a similar way as the answer, you will get an array like: `[['First'],['Second'],['Third']]`. This does matter if you want to directly perform string operations (such as `charAt`) on the elements in the list. – Rob W Jan 03 '12 at 17:24
0

if you are in an environment that supports modern ECMA additions, you can use Object.keys (docs here) or you can polyfill your own if you need to, something like this:

function getKeys(obj) {
    var ret = [], prop;

    for (prop in obj) {
        if ( Object.prototype.hasOwnProperty.call( obj, prop ) ) {
            ret.push( prop );
        }
    }

    return ret;
};

Usage:

var keys = getKeys({ foo: "a", bar: "b" }); // -> ['foo', 'bar']

hope that helps! cheers.

keeganwatkins
  • 3,636
  • 1
  • 14
  • 12