tags:

views:

93

answers:

2

I have a JSON String in this format:

{
  "supplier": {
    "mov_10": "love actually",
    "mov_1": "fare"
  },
  "quantity": 20,
  "success": true,
  "length":2
}

Now I want to create a select box below using the supplier object (using both the keys and values), like this:

<select id="selectme">
    <option id="mov_10">love actually</option>
    <option  id="mov_1">fare</option>
</select>

So how do I create it? I just want to know how to reach mov_10 and mov_1 in the object. Sorry for my bad English, but please help me.

Thanks.

+1  A: 

If I understood the question correctly, I think you might want to use something along this:

var jsonArray = ... ; // {"supplier": ... } (JS Object)
var supplierOptions = jsonArray.supplier;

// TODO: remember to set up selectme!

for(var optionId in supplierOptions) {
    if(!supplierOptions.hasOwnProperty(optionId)) {
        continue;
    }

    var optionValue = supplierOptions[optionId];

    // operate with name and value here (append to select ie.)
    $("#selectme").append('<option id="' + optionId + '">' + optionValue + '</option>');
}

The code probably could use some cleaning up. Hopefully it conveys the basic idea, though.

bebraw
You should use `if (!supplier.hasOwnProperty(optionId)) continue` to make sure you don't work with enumerable properties on the Object prototype. [`hasOwnProperty`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Object:hasOwnProperty)
Andy E
Good point! I will change that.
bebraw
what `if (!supplier.hasOwnProperty(optionId))` this do excatly?, please clear
diEcho
@bebraw Thankssssssssssssssssssssssssss
diEcho
+2  A: 

Use the for...in statement to iterate over keys:

for ( var k in someObject.supplier ) {
    someOption.value = k;
    someOption.text  = someObject.supplier[ k ];
}
Salman A
Doug Crockford on for..in: "Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object." http://javascript.crockford.com/code.html
nickf