lodash:对象中的深度合并

用户名

我想从此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的解决方案正在运行,但是我发现了问题,“子对象”包含与父对象相同的键名。

黑麦

您可以使用mapValues(),并具有一个回调,该回调value通过使用omit()并将自身合并()将返回的对象省略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>');  
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>

更新

为了响应您的更新,您仍然可以使用上面的原始解决方案,并进行一些调整,使用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>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章