Merge two objects without override

前端 未结 6 1489
北荒
北荒 2020-12-17 10:40

I have a defaultObject like that:

var default = {
    abc: \"123\",
    def: \"456\",
    ghi: {
       jkl: \"789\",
       mno: \"012\"
    }
};

6条回答
  •  旧巷少年郎
    2020-12-17 11:11

    I found that the easiest way to to this is to use mergeWith() from lodash ( https://lodash.com/docs/4.17.15#mergeWith ) which accepts a customizer function that decides what to do with every property merge. Here is one that is recursive :

    const mergeFunction = (objValue, srcValue) => {
      if (typeof srcValue === 'object') {
        _.mergeWith(objValue, srcValue, mergeFunction)
      } else if (objValue) {
        return objValue
      } else {
        return srcValue
      }
    }
    

提交回复
热议问题