【问题标题】:How to do a partial deep-merge based on changed property value of inner array如何根据内部数组的更改属性值进行部分深度合并
【发布时间】:2019-09-16 15:32:19
【问题描述】:

我正在尝试根据另一个关联的更改值数组来更新对象值数组。初始数组:

const primaryArray = [
  { 
  name: 'Product Family 1',
  products: [ {name: 'product 1', selected: false}, {name: 'product 2', selected: false}
  ]},
  { 
  name: 'Product Family 2',
  products: [ {name: 'product 3', selected: false}, {name: 'product 4', selected: false}
  ]},
];

更新项目的数组:

const updates = [
  { 
  name: 'Product Family 1',
  products: [ {name: 'product 2', selected: true}]
  },
  { 
  name: 'Product Family 2',
  products: [ {name: 'product 4', selected: true}]
  },
];

基本上只有更新数组中列出的产品应该在主数组中更改,同时仍保留现有未更改的产品

我在 Object.assign 和 _.mergeWith 上尝试了多种变体,由于 primaryArray 与“updates”数组中的元素数量不同,它们都没有按预期工作,例如:

    const newArray = primaryArray.forEach(obj => {
      return (updates.find(o => o.name === obj.name) || obj);
    });

我还尝试了多种变体,将 .map 与 .find 和 .forEach 结合使用,但没有任何运气。

预期的结果应该是:

const newArray = [
  { 
  name: 'Product Family 1',
  products: [ {name: 'product 1', selected: false}, {name: 'product 2', selected: true}
  ]},
  { 
  name: 'Product Family 2',
  products: [ {name: 'product 3', selected: false}, {name: 'product 4', selected: true}
  ]},
  ....
  // where the new Array will also inherit all other objects from the primaryArray
  name: 'Product Family 102',
  products: [ {name: 'product 1000', selected: false}
  ]},
];

【问题讨论】:

  • 注意:'updates' 数组的格式并不是一成不变的,如果有帮助,它的 'products' 属性可以改为字符串数组(产品名称)。跨度>

标签: javascript ecmascript-6 lodash


【解决方案1】:

我先把updates 变成一个哈希表:

 const updateByName = {};

 for(const { name, products } of updates)
   for(const {name: inner, selected } of products)
       updateByName[name + " > " + inner] = selected;

更新很简单:

 const result = primaryArray.map(({ name, products }) => ({
   name,
   products: products.map(({ name: inner, selected }) => {
      const update = updateByName[name + " > " + inner];
      return {
        name: inner,
        selected: update !== undefined ? update : selected,
      };
   })),
 }));

使用即将推出的null coalescing operator 会更加优雅。

【讨论】:

  • 太棒了,谢谢乔纳斯!关于使用哈希表的方式和原因仍然有点模糊,但效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-23
  • 1970-01-01
  • 2018-08-13
相关资源
最近更新 更多