lodash javascript对象只分配相同的密钥

时间:2017-04-04 02:21:13

标签: javascript ecmascript-6 lodash

const _ = require('lodash');
const tst = {
  a: 'A',
  b: 'B',
  c: 'C',
  d: 'D',
  e: {
    f: 'F',
    g: 'G'
  }
};

const tst2 = {
  e: {
    f: 'FF'
  },

  c: 'CC',

  h: 'HH'
}

console.log(_.assign(tst, tst2));
// { a: 'A', b: 'B', c: 'CC', d: 'D', e: { f: 'FF' }, h: 'HH' }
Object.assign(tst, tst2);
console.log(tst); // same with above result.
console.log(_.merge(tst, tst2));
// { a: 'A', b: 'B', c: 'CC', d: 'D', e: { f: 'FF', g: 'G' }, h: 'HH' }

我怎样才能得到结果

{ a: 'A', b: 'B', c: 'CC', d: 'D', e: { f: 'FF', g: 'G' } } ?

这意味着,我想更新tst对象。只有当前的密钥。 assign方法不仅有深拷贝问题,还有不必要的密钥(h)。 merge方法看起来合适但包含了不必要的密钥(h键)。 我现在可以使用其他方法处理这个问题。

我想知道我错过了在函数调用中使用一个内置(lodash或es6)实现的函数,如

console.log(someFunction(tst, tst2));
// { a: 'A', b: 'B', c: 'CC', d: 'D', e: { f: 'FF', g: 'G' } }

2 个答案:

答案 0 :(得分:0)

我认为这是您使用本机解决方案时最接近“c”键的特殊处理方法:

function updateKeyIfDifferentValue(obj, src) {
    Object.keys(obj).forEach(function(key) {
      if (src.hasOwnProperty(key)) {
        obj[key] = src[key];
      } else {
        obj[key] = obj[key];
      }
    });
    return obj;
}

let tst = {
  a: 'A',
  b: 'B',
  c: 'C',
  d: 'D',
  e: {
    f: 'F',
    g: 'G'
  }
};

let tst2 = {
  e: {
    f: 'FF'
  },
  c: 'CC',
  h: 'HH'
}

updateKeyIfDifferentValue(tst.e, tst2.e);
Object.assign(tst2, tst);
console.log(tst); // { a: "A", b: "B", c: "C", d: "D", e: {f: "FF", g: "G"} }

答案 1 :(得分:0)

您可以使用merge

var result = _.merge(tst, tst2);



var tst = {
  a: 'A',
  b: 'B',
  c: 'C',
  d: 'D',
  e: {
    f: 'F',
    g: 'G'
  }
};

var tst2 = {
  e: {
    f: 'FF'
  },

  c: 'CC',

  h: 'HH'
};

var result = _.merge(tst, tst2);

console.log(result);

body > div { min-height: 100%; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;
&#13;
&#13;