user1788736 user1788736 - 1 year ago 90
Javascript Question

How to construct array of objects inside $.each(?

I have little experience with array of objects so please bare with me.
My current code pushes the key into normal array but i want to push both key and value in to array of object. I appreciate if an expert show me how this can be done.Thanks

Javascript to create the object array:

var xml ='<?xml version="1.0" encoding="UTF-8"?> <dict><key>ItemLists</key> <array><dict><key>id</key> <string>1</string> <key>name</key> <string>fruits</string> <key>category</key> <string>US Fruits</string> <key>categoryIcon</key> <string></string> <key>country</key> <string>US</string> </dict> <dict><key>id</key> <string>2</string> <key>name</key> <string>Vegetable</string> <key>category</key> <string>Eu Vegetable</string> <key>categoryIcon</key> <string></string> <key>country</key> <string>EU</string> </dict> </array> </dict>';

xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);

var MyArray=[];
$(xml).find("array key").each(function(){
var key = $(this).text();
var value = $(this).next().text();
console.log(key + "=" + value);
//here i want to create array of objects instead of normal array
//and push both key and value to array of object

Object array sample that i want construct:

var myArray = [{
id: 1,
name: 'fruits',
category: 'US Fruits',
categoryIcon: '',
country: 'US'
}, {
id: 2,
name: 'Vegetable',
category: 'Eu Vegetable',
categoryIcon: '',
country: 'EU'
}, ];

I tried to print the array of objects like this but i got undefined for all

$.each(MyArray,function(j, object){

var div = "<tr id=\""+j+"\">\n" +
"<td>"+j+"</td>\n" +
"<td><img src=\""+ object.categoryIcon +"\" height=\"42\" width=\"42\"></td>\n" +
"<td>\n" +
"<a href=\"javascript:doit('id=" + + "&name=" + + "&category=" + object.category + "&categoryIcon=" + object.categoryIcon + "','"+ +"')\" onclick=\"selectLink(this);\">" + + "</a><br> \n" +


Answer Source

As you are collecting different objects, you should in fact have two loops: one for collecting the object properties for one dict, and one for collecting those objects into an array:

var myArray=[];
$(xml).find("array dict").each(function(){
    var obj = {};
    $(this).find("key").each(function () {
        var key = $(this).text();
        var value = $(this).next().text();  
        console.log(key + "=" + value);
        obj[key] = value;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download