合并两个Javascript对象数组的问题

时间:2016-08-26 18:40:15

标签: javascript jquery arrays

我有一个对象数组。我只想添加一个对象“WITH”索引。我不确定它是如何完成的。

这是我尝试过的:

//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
  ]
}

现在,我想在该数组中添加或删除另一个对象。

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

这不合并记录。而是创建两个对象,一个对象和另一个数组。

我该如何合并?带有DirtyData的newTimeRanges。(就像我想要3:“对象”)

有没有有效的方法呢?

由于

2 个答案:

答案 0 :(得分:2)

您需要将newTimeRanges的每个属性分别推送到temp数组。然后你可以连接dirtyData

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

或者你可以让newTimeRanges成为一个数组而不是一个对象,然后你可以写:

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

temp = newTimeRanges.concat(dirtyData);

答案 1 :(得分:1)

如果要将2个数组合并到第三个数组中,则必须使用concat,如下所示:

var temp = newTimeRanges.concat(dirtyData);

请参阅:Array.prototype.concat()

更改您的代码:

//RAW DATA:
var 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
}];

fetchedData.forEach(function(time) {
  delete time.startMinute;
  delete time.twelveHourFormat;
  delete time.endMinute;
});

console.log(fetchedData);

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

var temp = fetchedData.concat(dirtyData);

console.log(temp);