TechnoCorner TechnoCorner - 3 months ago 15
jQuery Question

issue merging two Javascript object arrays

I have an object array. I just want to add one more object "WITH" an index. I'm not sure how it's done.

This is what I've tried:

//RAW DATA:
this.fetchedData = [{
"startMinute": 0, //Remove
"annotation": "All Day",
"twelveHourFormat": "12am-11:59pm", //Remove
"timeRange": "00:00-23:59",
"endMinute": 1439 //Remove
}, {
"startMinute": 300, //Remove
"annotation": "Morning",
"twelveHourFormat": "5am-8:59am", //Remove
"timeRange": "05:00-08:59",
"endMinute": 539 //Remove
}]

var newTimeRanges = [];
var temp = []; //Final array(assuming i need one)

newTimeRanges = _.each(this.fetchedData, function(time) {
delete time.startMinute;
delete time.twelveHourFormat;
delete time.endMinute;
});

//DATA AFTER REMOVAL

newTimeRanges = {
0: {
annotation: "All Day",
timeRange: "00:00-23:59"
},
1: {
annotation: "Evening",
timeRange: "16:00-18:00"
}
}

//DATA TO BE MERGED
var dirtyData = [{
"timeRange": "3am-6am",
"annotation": earlymorning
}];

//Essentially (timeRange+DirtyData)


//Expected Output to be sent for backend
{
"times": [{
"annotation": "All Day",
"timeRange": "00:00-23:59"
}, {
"annotation": "Morning",
"timeRange": "05:00-08:59"
},
//Add my new Data here
]
}


Now, I want to add or remove another object to that array.

temp.push(newTimeRanges);
temp.push(dirtyData);


This does not merge the records. Instead creates two objects one object and another array.

How can I merge. newTimeRanges with DirtyData. (Like I want 3: "Object")

Is there any efficient way of doing this?

Thanks

Answer

You need to push each property of newTimeRanges separately onto the temp array. Then you can concatenate dirtyData.

$.each(newTimeRanges, function(key, obj) {
    temp.push(obj);
}
temp = temp.concat(dirtyData);

Or you could have made newTimeRanges an array instead of an object, and then you could write:

newTimeRanges = [
    {
        annotation:"All Day",
        timeRange:"00:00-23:59"},
    {
        annotation:"Evening",
        timeRange:"16:00-18:00"}
];

temp = newTimeRanges.concat(dirtyData);
Comments