0

I 'm trying to add the data in to json objects using for loop, but push method is not working because it adds the object in to the json array, Any idea to add datas in to json object?

My Code:

    var data = [
        { Name: "Jake", Gender: "Male", Address: "Address1" },
        { Name: "Laura", Gender: "Female", Address: "Address2" },
    ];

    for (var i = 0; i < data.length; i++) {
        if (data[i].Gender == "Male") {
            data[i].push({ Icon: "image/male.png" });
        } else {
            data[i].push({ Icon: "image/female.png" });
        }
    }

    var result = data;

I need the result as:

result = [
            { Name: "Jake", Gender: "Male", Address: "Address1", Icon: "image/male.png" },
            { Name: "Laura", Gender: "Female", Address: "Address2", Icon: "image/female.png" },
        ];

The data Icon is to be added in the every object based on the if condition

Suganth G
  • 5,136
  • 3
  • 25
  • 44

2 Answers2

4

There is only one Icon, so you can set it directly:

for (var i = 0; i < data.length; i++) {
    if (data[i].Gender == "Male") {
        data[i].Icon = "image/male.png";
    } else {
        data[i].Icon = "image/female.png";
    }
}

Before, you should have seen an error in your console as data[i] is an Object (not an Array) and does not have any method push

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • 2
    I would *also* say that what he's referring to as JSON it's an invalid JSON, rather an array populated with object literals. – Roko C. Buljan Aug 21 '14 at 07:49
0

Here's what you need to do:

var data = [
        { Name: "Jake", Gender: "Male", Address: "Address1" },
        { Name: "Laura", Gender: "Female", Address: "Address2" },
    ];
    for (var i = 0; i < data.length; i++) {
        if (data[i].Gender == "Male") {
            data[i].Icon = "image/male.png";

        } else {
            data[i].Icon = "image/female.png";
        }
    }

    var result = data;
    alert(result[0].Icon);
    alert(result[1].Icon);

Please see your Working fiddle here

Abdul Jabbar
  • 2,573
  • 5
  • 23
  • 43