使用数组方法根据具有相同 id 的另一个数组的元素的存在设置数组元素 object 属性

set array element object property based on the presence of an element of another array with the same id using array methods

标题很啰嗦,所以我会用一个例子和一个工作代码来证明这个想法:

考虑商店中可用的大型歌曲库。让我们称之为“bigarray”。一位客户拥有 his/her 自己从该商店购买歌曲的个人图书馆:“smallArray”。 BigArray 元素具有 属性“已购买”。如果两个数组的歌曲之间的 id 匹配,我需要将 属性 设置为“true”。一个工作代码示例:

for (let i = 0; i < bigArray.length; i++) {
  for (let j = 0; j < smallArray.length; j++) {
    if (bigArray[i].id === smallArray[j].id) {
      bigArray[i].purchased = true;
    }
  }
}

有没有一种方法可以使用数组方法(如 map、filter 等)在一行中使用谓词函数而不是双 for 循环来进行编程?

您可以先从 smallArray 中的对象创建一组 ID,然后在 bigArray 上使用 .map() 更新 purchased 属性 到 truefalse 基于集合是否具有大数组中当前对象的id:

const smallSet = new Set(smallArray.map(({id}) => id));
const result = bigArray.map(obj => ({...obj, purchased: smallSet.has(obj.id)}));

您还可以使用 .some() 来确定您的 smallArray 是否有一个对象与您的 bigArray 中的 id 相匹配,这具有更差的时间复杂度 O(n* k) 与使用 O(n+k) 的集合相比,但更适合“单行”的是你所追求的:

const result = bigArray.map(obj => ({
  ...obj, 
  purchased: smallSet.some(item => item.id === obj.id)
}));