微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Js的过滤和映射过程中获得仅具有唯一ID的新数组?

如何解决如何在Js的过滤和映射过程中获得仅具有唯一ID的新数组?

我正在尝试从标签和关键字中获得dropwwon项目。我尝试将它们采用相同的格式进行过滤和映射,如下所示:

  const productsWithTags = products
          .filter(product => !!product.tagId)
          .map(item => ({
            id: item.tagId,name: item.tagName,}))

问题在于它会添加重复项,因为某些产品具有相同的tagIds,如何使该数组唯一?

解决方法

首先,您必须通过tagId选择不同的项目,然后映射结果

const products= [{tagId:1,tagName:"Tag 1"},{tagId:2,tagName:"Tag 2"},{tagId:3,tagName:"Tag 3"},{tagId:1,tagName:"Tag 1-2"},tagName:"Tag 3-2"},tagName:"Tag 2-2"}]
const productsWithTags = products
          .filter(function(value,index,self){return self.indexOf(self.find(item =>item.tagId==value.tagId)) === index})
          .map(item => ({
            id: item.tagId,name: item.tagName,}))
console.log(productsWithTags)

,

您不必创建tagId属性到Boolean的属性,而必须创建一个查找表来告诉您是否已查看/访问过某项的tagId,然后进行过滤根据该结果。

您可以在下面看到带有注释的有效示例。

const products = [
  {
    tagId: 'a',tagName: 'Tag A'
  },{
    tagId: 'b',tagName: 'Tag B'
  },{
    tagId: 'a',{
    tagId: 'c',tagName: 'Tag C'
  }
];

function uniqueBy(property) {
  let seen = Object.create(null); // closure,tells us the already seen id's
  return function (item) {        // predicate function
    let key = item[property];     // get the "key" value (here: tagId)
    if (seen[key] == null) {      // is the key not inside the seen closure?
      seen[key] = 1;              // then add it and
      return true;                // accept the item
    }
    return false;                 // otherwise reject the item
  };
}

const result = products.
  filter(uniqueBy('tagId')).      // use "uniqueBy" to create a predicate
  map(product => {
    return {
      id: product.tagId,name: product.tagName
    };
  });
  
console.log(result);

提示:您可以通过避免一个迭代步骤来提高性能。怎么样?使用.reduce代替.filter.map

const products = [
  {
    tagId: 'a',tells us the already seen id's
  return function (item) {        // predicate function
    let key = item[property];     // get the "key" value (here: tagId)
    if (seen[key] == null) {      // is the key not inside the seen closure?
      seen[key] = 1;              // then add it and
      return true;                // accept the item
    }
    return false;                 // otherwise reject the item
  };
}


function filterMap(filterer,mapper) {
  return function (accumulator,item) {
    return filterer(item)
      ? [...accumulator,mapper(item)]
      : accumulator;
  }
}

const result = products.
  reduce(
    filterMap(
      uniqueBy('tagId'),product => {
          return {
            id: product.tagId,name: product.tagName
          };
      }
    ),[]
  );
  
console.log(result);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。