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

issue merging two Javascript object arrays

本文关键字:对象 数组 问题 Javascript 两个 合并      更新时间:2023-09-26

我有一个对象数组。我只是想添加一个对象"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);

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

如何合并。newTimeRanges with DirtyData。 (Like I want 3: "Object")

是否有任何有效的方法来做到这一点?

谢谢

您需要将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);

如果你想将两个数组合并成第三个数组,你必须使用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);