Intersect and merge two array of objects

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

I have two arrays:

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


        
2条回答
  •  情话喂你
    2021-01-29 12:21

    The most efficient way I can see (although maybe not leveraging JS predefined functions) is making up a dictionary with the name values as the keys.

    You can go through the first array and populate the dictionary. Then you can iterate through the second array and add each element to the dictionary if it doesn't contain the name or merge the objects if it does.

    Example:

    var odd = [
        { name : "1", extraProp1 : "propValue1" },
        { name : "3",  extraProp1 : "propValue2"}
    ];
    
    var even = [
        { name : "1", extraProp2 : "prop1" },
        { name : "2", extraProp2 : "prop2"},
        { name : "4", extraProp2 : "prop3" }
    ]; 
    
    var combinedDictionary = {}
    
    for(let obj of odd) {
      combinedDictionary[obj.name] = obj;
    }
    
    for(let obj of even) {
      combinedDictionary[obj.name] = { 
        ...(combinedDictionary[obj.name] || {}),
        ...obj
      };
    }
    
    var result = Object.keys(combinedDictionary).map(key => combinedDictionary[key]);
    
    console.log(result);

提交回复
热议问题