0
    var data = {};
    $('.content').each(function(i){
        var id = $(this).attr('id'),
            level = $(this).attr('level'),
            name = $(this).find('textarea').val(),
            data2 = {
                i:[
                    {
                    "id": id,
                    "level": level,
                    "name": name
                    }
                ]
            };
            $.extend(data, data2);
    });

In the object data2 i want the array i to be an auto increasing number based on the .each. But it keeps naming it i.

4 Answers 4

4
data2 = {};
data2[i] = {
    "id": id,
    "level": level,
    "name": name
};
Sign up to request clarification or add additional context in comments.

Comments

1

Property names are treated literally in Javascript, whether or not there are any variables with that name.

However, you redefine the object on every iteration of the loop. Your code should probably look like this:

data2[i] = {
    id: id,
    level: level,
    name: name
};

Note that I have removed the array literal -- the [] around the object literal. I can't imagine you need it, but you could always put it back in if you genuinely did.

Comments

1

Maybe you should do:

        data2[i] = [{
                "id": id,
                "level": level,
                "name": name
                }];

Comments

1
var data = {};
$('.content').each(function(i) {
    var id = $(this).attr('id'),
        level = $(this).attr('level'),
        name = $(this).find('textarea').val(),
        data2 = {};
    data2[i] = [{
        "id": id,
        "level": level,
        "name": name}];
};                   
$.extend(data, data2);

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.