首页 > 解决方案 > 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"
            }
        }
    ];

谁能帮帮我,我已经测试了这里找到的各种解决方案,但不适用于我的阵列

标签: jqueryarraysmultidimensional-array

解决方案


我找到了解决方案:-)

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] 放在第二个数组中


推荐阅读