在这种情况下,如何为lodash _.Mergewith编写定制功能?

发布于 2025-02-05 07:07:44 字数 447 浏览 4 评论 0原文

我有两个这样的对象:

var obj3 = {
    customer_id: 1,
    products: { id: 1, name: "Car" },
  };

  var obj4 = {
    customer_id: 1,
    products: { id: 2, name: "Dress" },
  };

预期的对象是:

result = {
    customer_id: 1,
    products: [
      { id: 1, name: "Car" },
      { id: 2, name: "Dress" },
    ],
  };

在这种情况下,如何编写function customizer(){}? 非常感谢您的帮助,我们欢迎以不同的方式提供其他解决方案。

I have two objects like that:

var obj3 = {
    customer_id: 1,
    products: { id: 1, name: "Car" },
  };

  var obj4 = {
    customer_id: 1,
    products: { id: 2, name: "Dress" },
  };

and the expected object is:

result = {
    customer_id: 1,
    products: [
      { id: 1, name: "Car" },
      { id: 2, name: "Dress" },
    ],
  };

How can i write function customizer(){} in this situation?
Thanks so much for your help, and i'll be welcome for other solution with different way.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挽容 2025-02-12 07:07:44

将对象合并到新对象({})。将合并值的默认值设置为空数组。如果密钥是产品 concat。如果没有返回未定义,则将使用merge()的标准逻辑:

const obj3 = { customer_id: 1, products: { id: 1, name: "Car" }, };
const obj4 = { customer_id: 1, products: { id: 2, name: "Dress" }, };

const result = _.mergeWith({}, obj3, obj4, (v1 = [], v2 = [], key) =>
  key === 'products' ? v1.concat(v2) : undefined
)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Merge the objects to a new object (the {}). Set the default values of the merged values to empty arrays. If the key is products concat them. If not return undefined, so the standard logic of _.merge() would be used:

const obj3 = { customer_id: 1, products: { id: 1, name: "Car" }, };
const obj4 = { customer_id: 1, products: { id: 2, name: "Dress" }, };

const result = _.mergeWith({}, obj3, obj4, (v1 = [], v2 = [], key) =>
  key === 'products' ? v1.concat(v2) : undefined
)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文