how to push an object like this in jquery?

Vincent815 picture Vincent815 · Mar 9, 2014 · Viewed 15.2k times · Source

may I know how to push var obj= [{}] in .each? for example like this.

 $.each(maintasks_row, function(index, maintasks_val) { 
                obj.push([{
                    "name" : maintasks_val.task_name,
                    "desc" : "",
                    "values" : [{
                        "from" : "/Date("+maintasks_val.time_start+")/",
                        "to" : "/Date("+maintasks_val.time_end+")/",
                        "label": maintasks_val.task_name,
                        "customClass" : "ganttRed"
                    }]
                }]);
            }); 

I'm using this for $(".gantt").gantt({source: obj});

On this site the var data is [{}] is this an object? and how can I insert it?

thank you

Answer

Rob Sedgwick picture Rob Sedgwick · Mar 9, 2014

.push does not require you delcare it as an array ( like you tried obj.push([{ - unless of course you are pushing an array into an array

Just simply ...

obj.push({"name" : maintasks_val.task_name, ..

adds a new single item intto the array


Update as comment , yes, declare obj as a typeof array first

var obj=[];

This is now the same as the data array you have shown in your docs example - and we can now .push() into it.