Suganth G
Suganth G

Reputation: 5156

How to add the data into json object?

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

Upvotes: 0

Views: 365

Answers (2)

Abdul Jabbar
Abdul Jabbar

Reputation: 2573

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

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78525

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

Upvotes: 4

Related Questions