gpt4 book ai didi

javascript - lodash:对象的深度合并

转载 作者:行者123 更新时间:2023-11-28 10:48:56 25 4
gpt4 key购买 nike

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

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 的解决方案正在工作,但我发现问题,“子对象”包含与父对象相同的键名称。

最佳答案

您可以使用mapValues() ,并有一个回调,通过使用 omit() 返回每个带有省略的对象。和 merge()它与该本身。

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>

关于javascript - lodash:对象的深度合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37115693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com