我想在对象中进行合并,从这个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"} }
}
进入这个对象:
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的解决方案正在运作,但我发现了问题,"孩子反对"包含与父对象相同的键名。
答案 0 :(得分:0)
您可以使用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>');
本身。
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>
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>');
<强>更新强>
为了响应您的更新,您仍然可以使用上面的原始解决方案,稍微进行一些调整,使用mapKeys()从给定前缀转换每个对象键(如果它来自合并源)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js"></script>
beach_life-normal.jpg