I want to make merge in objects, from this 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"} }
}
into this 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: solution from @ryeballar is working, but I found the problem, "children object" consist the same key name like a parent object.
You can make use of mapValues() , and have a callback that returns each object with an omitted value
by using omit() and merge() it with that value
itself.
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>
UPDATE
In response to your update, you can still make use of the original solution above, with a little bit of tweaking where you use mapKeys() to transform each object key from a given prefix if it exists from the merge source.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.