合并两个Javascript对象数组的问题
issue merging two Javascript object 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);
这不会合并记录。而是创建两个对象一个对象和另一个数组。
如何合并。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);
相关文章:
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 在Javascript中转换对象数组
- 在JavaScript中通过索引从对象数组中获取值
- Backbone虹吸以获取对象数组
- 如何在DataTables 2.1中迭代对象数组
- Javascript-根据赋值顺序,按键合并对象数组
- 将事件附加到对象/数组
- jQuery$.inArray()总是返回-1和一个对象数组
- javascript处理一个对象数组以获得一个新的对象数组
- javascript在数组中获取对象数组中键的所有不同值
- 在对象数组中查找多个值的d3范围
- Undercore.js获取对象数组中键对象的值
- 在mongoose中使用正则表达式在对象数组中进行查询搜索
- 如何通过json对象数组为嵌套对象赋值
- 如何循环通过2个对象数组并通过匹配id进行合并
- 为对象数组创建列表项
- 如何使用javascript合并两个对象数组
- JSON到对象数组,并向每个对象添加项
- JavaScript:从对象数组中获取唯一值及其计数
- 按不同项目对对象数组进行排序