jquery - Jquery 按 id 比较 2 种类型的数组并删除 id 不相等的对象
问题描述
我有 2 种类型的数组,我需要删除第一个数组中不存在 id 的对象,这是我的数组
var cityArr = [
"1:City 1",
"2:City 2",
"3:City 3",
];
var cityEvent = [
{
"2": {
"day": "13",
"hour": "10:00"
},
"3": {
"day": "15",
"hour": "20:30"
},
"1": {
"day": "12",
"hoyr": "17:50"
},
"4": {
"day": "18",
"hour": "19:00"
},
}
];
// return new array without id 4
var cityEventUpdate = [
{
"2": {
"day": "13",
"hour": "10:00"
},
"3": {
"day": "15",
"hour": "20:30"
},
"1": {
"day": "12",
"hoyr": "17:50"
}
}
];
谁能帮帮我,我已经测试了这里找到的各种解决方案,但不适用于我的阵列
解决方案
我找到了解决方案:-)
var props = ['id'];
var result = cityArr.filter(function(o1){
// filter out (!) items in result2
return !cityEvent.some(function(o2){
return o1.id === o2.id; // assumes unique id
});
}).map(function(o){
// use reduce to make objects with only the required properties
// and map to apply this to the filtered array as a whole
return props.reduce(function(cityEventUpdate, id){
cityEventUpdate[id] = o[id];
return cityEventUpdate;
}, {});
});
console.log(JSON.stringify(cityEventUpdate))
我的错误是将 [0] 放在第二个数组中
推荐阅读
- c# - 当焦点位于单选按钮或复选框上时按“c”时表单关闭
- node.js - 嵌套对象数组更新mongodb
- java - 反转 int 数组,但结果只完成了一半
- c# - 启用 TLS1.2 后 Asp.net 发送邮件失败
- rest - Spring Security 为两个不同的 url 配置两个不同的身份验证
- java - 从 Java jar 调用时,Jython 代码抛出 ImportError
- c# - 如何在通用 Windows 平台中添加 360 度图像视图
- r - 在 Tripadvisor 上使用 XML R 包的带单引号的 XML 属性
- javascript - 输入的javascript分布
- javascript - 如何在Angular中的对象数组内执行函数