Intersect and merge two array of objects

后端 未结 2 1781
轮回少年
轮回少年 2021-01-29 11:53

I have two arrays:

var odd = [
    { name : "1", extraProp1 : "propValue1" },
    { name : "3",  extraProp1 : "propValue2"         


        
2条回答
  •  情歌与酒
    2021-01-29 12:29

    Indeed, in your attempt you are correctly filtering a, but you have no code that merges two objects.

    I would also use a Map for faster lookup than with a nested call of filter:

    function merge(a, b, prop) {
        let map = new Map(b.map(o => [o[prop], o]));
        return a.reduce((acc, o) => {
            let match = map.get(o[prop]);
            return match ? acc.concat({ ...o, ...match }) : acc;
        }, []);
    }
    
    
    var odd = [
        { name : "1", extraProp1 : "propValue1" },
        { name : "3",  extraProp1 : "propValue2"}
    ];
    
    var even = [
        { name : "1", extraProp2 : "prop1" },
        { name : "2", extraProp2 : "prop2"},
        { name : "4", extraProp2 : "prop3" }
    ]; 
    
    console.log(merge(odd, even, "name"));

    The { ...o, ...match } part performs the actual merge of two objects that was missing in your solution.

提交回复
热议问题