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

2
  • See this ... may be useful Commented Aug 21, 2014 at 7:50
  • i have already seen that link Bhushan , They using push method Commented Aug 21, 2014 at 7:53

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I would also say that what he's referring to as JSON it's an invalid JSON, rather an array populated with object literals.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.