【问题标题】:lodash: deep merge in objectslodash:对象中的深度合并
【发布时间】:2016-05-09 12:20:56
【问题描述】:

我想从这个 obj 中合并对象:

objs = {
  one: { description: "value", amount: 5, value: { description: "value desc", identifier: "some text"} },
  two: { description: "value", amount: 5, value: { description: "value desc", identifier: "some text"} }
}

进入这个 obj:

objs = {
  one: { original_description: "value", amount: 5, description: "value desc", identifier: "some text" },
  two: { original_description: "value", amount: 5, description: "value desc", identifier: "some text" }
}

UPD: @ryeballar 的解决方案正在运行,但我发现了问题,“子对象”包含与父对象相同的键名。

【问题讨论】:

    标签: javascript object lodash


    【解决方案1】:

    您可以使用mapValues(),并通过使用omit()merge() 以及value 本身来返回带有省略value 的每个对象。

    var objs = {
      one: { description: "value", amount: 5, value: { identifier : "some text"} },
      two: { description: "value", amount: 5, value: { identifier : "some text"} }
    };
    
    var result = _.mapValues(objs, i => _(i).omit('value').merge(i.value).value());
                   
    document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');  
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"&gt;&lt;/script&gt;

    更新

    为了响应您的更新,您仍然可以使用上面的原始解决方案,稍作调整,您可以使用 mapKeys() 从给定前缀转换每个对象键(如果它存在于合并源)。

    var objs = {
      one: { description: "value", amount: 5, value: { description: "value desc", identifier: "some text"} },
      two: { description: "value", amount: 5, value: { description: "value desc", identifier: "some text"} },
      three: { description: "value", amount: 5, value: null },
      four: { description: "value", amount: 5 }
    }
    
    function mergeFromKey(object, mergeKey, prefix) {
      return _.mapValues(object, item => 
        _(item).mapKeys((v, k) => (_.get(item[mergeKey], k)? prefix: '') + k)
        .omit(mergeKey)
        .merge(item[mergeKey])
        .value()
      );
    }
    
    var result = mergeFromKey(objs, 'value', 'original_');
    
    document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"&gt;&lt;/script&gt;

    【讨论】:

    • 还有一个问题(如果value = null,这个函数会坏掉,需要加上check if item[mergeKey] != null 然后merge,错误示例:jsfiddle.net/88xp1osn
    • @ShootingStar 请检查更新,我在mapKeys() 回调中使用了_.get()
    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 2017-01-07
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2015-06-03
    相关资源
    最近更新 更多