开发者问题收集

React 在对象数组中查找

2022-03-17
2305
  export const data = [
    {
      id: "card1",
      img: require("./image/prosperity.jpg"),
      title: "Increasing Prosperity With Positive Thinking",
      tags: ["Art", "Design"],
      desc: "Increasing prosperity in our lives can be accomplished by having the right frame of mind. The truth is, our thoughts are very powerful. They are capable of influencing every aspect of our daily lives, from our physical health to our social behaviors. I'm sure you've heard the adage, 'As you think, so shall you be.'",
    },
    {
      id: "card2",
      img: require("./image/motivation.png"),
      title: "Motivation Is The First Step To Success",
      tags: ["Culture"],
      desc: "Knowing yourself is the first, and a very critical step in the process of planning your future. How can you figure out what you want to do with your life if you don’t know: What am I going to do with the  rest of my life? What is my dream job? What do I enjoy doing? What’s my passion? What kind of career fits my personality?",
    },
    {
      id: "card3",
      img: require("./image/success.jpg"),
      title: "Success Steps For Your Personal Or Business Life",
      tags: ["Art", "Culture"],
      desc: "Don’t forget the preparation. Success needs hard work. Successful people do not see failures as failures.Just set something gratifying to indulge in after completing a certain undertaking. If you want to succeed, surround yourself with the right kind of people who will support and encourage you all the way.",
    },
    {
      id: "card4",
      img: require("./image/teamwork.png"),
      title: "Learn to tell stories",
      tags: ["Art", "Design", "Culture"],
      desc: "People love stories because they connect them with themselves on an emotional level. Marketers who know how to tell great stories in their marketing campaigns achieve outstanding results. Read more and be comprehensively developed. This will help you to find unusual ideas.",
    },
    {
      id: "card5",
      img: require("./image/performance.jpg"),
      title: "Define performance indicators",
      tags: ["Art", "Design"],
      desc: "Marketing is not the same as ten years ago. Today, companies want to understand what exactly the budget went for. Therefore, it is important before marketing activities to determine goals and performance indicators. So you will improve the results and be able to convey to your leadership your value as a frame. Often reports are provided monthly, indicators should be clear and clearly demonstrate the results.",
    },
    {
      id: "card6",
      img: require("./image/time.jpg"),
      title: "Time management",
      tags: ["Art", "Culture"],
      desc: "Good specialists are able to correctly plan projects and create a schedule for completion of work. Therefore, they complete tasks on time. They know how to properly allocate resources and ensure the specified launch date, relate to it with trepidation and do everything possible to ensure that everything is done on time.",
    },
    {
      id: "card7",
      img: require("./image/income.jpg"),
      title: "Focus on income",
      tags: ["Design", "Culture"],
      desc: "Marketers focused on generating revenue for the company are in great demand. Therefore, if all your efforts are aimed precisely at this, you will find great success. According to a study by  Fournaise Marketing Group, 78% of managers believe that marketing is not focused on achieving financial performance. Link marketing activities with analytics, consider the short-term and long-term goals of the enterprise, and you will become a good professional in this field. ",
    },
    {
      id: "card8",
      img: require("./image/workdata.jpg"),
      title: "Work with data",
      tags: ["Culture", "Design"],
      desc: "Learn how to use the data for your own purposes. Master your analytics tools, improve your Excel knowledge. In the coming decades, employers will look for just such specialists who can work with a huge array of data and use it to develop their business and achieve financial performance.",
    },
  ];

我想按标签过滤。我有按钮全部 - 文化 - 艺术 - 设计。

const filterItem = curcat => {
  const newItem = Data.filter(newVal => {
    return newVal.tags.find(el => el === curcat);
  });
  setItem(newItem);
};

我如何按标签过滤此对象数组?

3个回答

您需要通过数组进行映射,然后对标签使用过滤函数,如果发现标签,则将对象推送到 filterData 并转至下一个对象。

const filtredData = [];
data.map((item) => {
 const search = item.tags.filter((tagItem) => {
    if(tagItem === "Art"){
      // push object to array
      filtredData.push(item)
      return
    }
  })
})
Paiman Rasoli
2022-03-17

也许此代码适用于您正在做的事情

function filterBytag(tag){
  const result = data.filter((dataItem) => {
    if(dataItem.tags.includes(tag)){
      return true;
    }
    return false;
  });
  return result;
}
Arlle Brasil
2022-03-17

看看这个,兄弟:

const filterByProp = prop => val => {
  return data.filter(obj => {
    const currentValue = obj[prop]
    return Array.isArray(currentValue) ? currentValue.includes(val) : val == currentValue
  })
}
const filterByTags = filterByProp('tags');

console.log(filterByTags('Silliness')) // I added Silliness to one of the tags so it was unique

这给你以下:

[
  {
    id: 'card2',
    title: 'Motivation Is The First Step To Success',
    tags: [ 'Culture', 'Silliness' ],
    desc: 'Knowing yourself is the first, and a very critical step in the process of planning your future. How can you figure out what you want to do with your life if you don’t know: What am I going to do with the  rest of my life? What is my dream job? What do I enjoy doing? What’s my passion? What kind of career fits my personality?'
  }
]

Ramda 是一个很酷的功能库,用于这些类型的操作。我写了一个很酷的两行代码,导入它们的函数 propSatisfiesincludesfilter 可以得到相同的结果。

const tagsContain = tag => propSatisfies(includes(tag), 'tags')
const filterByTag = tag => filter(tagsContain(tag), data)
console.log(filterByTag('Silliness'))
Joshua Wood
2022-03-17