简体   繁体   English

Angular 比较数组并更新其中一个

[英]Angular compare array and update one of it

I have this two sets of array, I need to compare them and if the object from 2th array found on 1st array, I need to update the status on 1st array to true.我有这两组数组,我需要比较它们,如果在第一个数组上找到来自第二个数组的 object,我需要将第一个数组的状态更新为真。 On angular how to massage the data, thanks!关于angular如何按摩数据,谢谢!

Below are sample of array,以下是数组示例,

arr1 = [
  {id: 1, status: false},
  {id: 2, status: false},
  {id: 3, status: false}
];

arr2 = [
  {id: 4},
  {id: 5},
  {id: 2}
];

Even though you have not provided any (faulty) code from yourself, I understand that it sometimes can be difficult to even begin with such a thing.即使您自己没有提供任何(错误)代码,但我知道有时甚至很难从这样的事情开始。

In this case, you should find a beginning point.在这种情况下,您应该找到一个起点。 You can use the source array ( arr1 ) as starting point, or arr2 .您可以使用源数组 ( arr1 ) 作为起点,或者arr2 If arr2 is tiny, it's quicker to use this as starting point.如果arr2很小,则使用它作为起点会更快。 The bigger arr2 gets, the more you might want to start with arr1 , because that solution is more readable (subjective). arr2 越大,您可能希望从arr1开始越多,因为该解决方案更具可读性(主观)。

With arr2 as starting point, you can use the forEach method, in combination with find :arr2为起点,您可以结合使用forEach方法和find

arr2.forEach((item) => {
  const target = arr1.find(({ id }) => item.id === id);

  if (target) {
    target.status = true;
  }
});

With the arr1 as starting point, you can use the map method.arr1为起点,可以使用map方法。 This will make a new array in place, which is usually a good thing to do, considering angular's change detection system:考虑到 Angular 的变化检测系统,这将创建一个新数组,这通常是一件好事:

arr1 = arr1.map((item) => ({
  ...item,
  status: arr2.some(({ id }) => item.id === id)
});

This will also create a new object reference.这也将创建一个新的 object 参考。 Depending on your data set, performance might be an issue, but this will only be noticable if you are processing +10.000 objects (depending on the complexity of your objects).根据您的数据集,性能可能是一个问题,但只有在处理 +10.000 个对象时才会注意到这一点(取决于对象的复杂性)。

If you do not want a status: true be overwritten to false on arr1 , you need to add an extra condition:如果您不想在arr1上将status: true覆盖为false ,则需要添加一个额外的条件:

arr1 = arr1.map((item) => ({
  ...item,
  status: item.status || arr2.some(({ id }) => item.id === id)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM