jQuery深度扩展,仅替换值,不希望添加新键

时间:2017-09-28 11:31:18

标签: javascript jquery

例如。我有两个json对象,

首先:

{
  "surname" : "Raghuvanshi",
  "work" : {
     "title": "title1"
  },
  "name" : "Navin"
}

第二:

{
  "work" : {
     "title": "title2",
     "field": "field2"
  },
  "name" : "Navin"
}

我想要一个函数,它将使用仅存在于第一个对象上的键将所有第二个对象值分配给第一个对象

我想要的是什么:

{
  "surname" : "Raghuvanshi",
  "work" : {
     "title": "title2"
  },
  "name" : "Navin"
}

jQyery.extend(true, first, second)给出的内容

{
  "surname" : "Raghuvanshi",
  "work" : {
     "title": "title2",
     "field": "field2"
  },
  "name" : "Navin"
}

更新:我知道用jQuery.extend()无法做到这一点,你可以为我提供一个javascript递归函数来代替它。

2 个答案:

答案 0 :(得分:2)

这样的事情: -

var one = {
    name: "Navin",
    surname: "Raghuvanshi",
    work: {
        title: "title1",
    }
};
var two = {
    name: "Navin",
    work: {
        title: "title2",
        field: "field2"
    }
};

function mergeValues(primary, mergeFrom) {
    var primaryKeys = Object.keys(primary);
    primaryKeys.forEach(function (value, key) {
        if (typeof mergeFrom[value] !== "undefined") {
            if (typeof mergeFrom[value] !== "object") {
                primary[value] = mergeFrom[value];
            }

            if (typeof mergeFrom[value] === "object" && typeof primary[value] === "object") {
                primary[value] = mergeValues(primary[value], mergeFrom[value])
            }
        }
    });


    return primary;
}

var mergedObject = mergeValues(one, two);

console.log(mergedObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

我找到了extend函数from nickf's answer

function extend (target, source) {
  target = target || {};
  for (var prop in source) {
    if (typeof source[prop] === 'object') {
      target[prop] = extend(target[prop], source[prop]);
    } else {
      target[prop] = source[prop];
    }
  }
  return target;
}

只需将其更改为。

function extend (target, source) {
  target = target || {};
  for (var prop in target) {
    if (typeof target[prop] === 'object' && typeof source[prop] === 'object') {
      target[prop] = extend(target[prop], source[prop]);
    } else if (typeof target[prop] == typeof source[prop]) {
      target[prop] = source[prop];
    }
  }
  return target;
}

https://jsfiddle.net/m2wbpggu/2/