3

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.

diEcho
  • 50,018
  • 37
  • 156
  • 230
  • 2
    I cleaned up your question a little bit but didn't change your reference to a "JSON object." This is actually incorrect. There is no such thing as a "JSON object." What you have is just a regular JavaScript object in object literal notation. You're confusing it with "JSON string," which is a string specifically formatted in a subset of object literal notation. – Jimmy May 28 '10 at 07:22
  • i may be incorrect for naming but i shown the array i get. – diEcho May 28 '10 at 08:41

2 Answers2

2

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
  • 229,425
  • 77
  • 398
  • 489
  • 2
    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 May 28 '10 at 08:21
0

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.

Juho Vepsäläinen
  • 24,765
  • 11
  • 73
  • 98
  • 1
    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 May 28 '10 at 07:16
  • what `if (!supplier.hasOwnProperty(optionId))` this do excatly?, please clear – diEcho May 28 '10 at 09:05
  • Thankssssssssssssssssssssssssss – diEcho May 28 '10 at 09:05