Home > database >  React find in array of an object
React find in array of an object

Time:03-18

  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.",
    },
  ];

I want to filter by tags. I have buttons All - Culture - Art -Design.

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

How can I filter this object array by tags?

CodePudding user response:

you need to map through the array and then a filter function on the tags if tag found push object to filterData and escape to the next object.

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

CodePudding user response:

function findInArrayOfAnObject(arr){
  arr.map(item=>{
     for(const key in item){
        if(Array.isArray(item[key])){
          // key console.log(key) 
          // value item[key]
       }
     }
  })
};

CodePudding user response:

Maybe this code works for what you are doing

function filterBytag(tag){
  const result = data.filter((dataItem) => {
    if(dataItem.tags.includes(tag)){
      return true;
    }
    return false;
  });
  return result;
}

CodePudding user response:

Check this out, bro:


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

This gives you the following:

[
  {
    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 is a cool, functional library for these kinds of manipulations. I wrote a cool two liner that yields the same result importing their functions propSatisfies, includes and filter

const tagsContain = tag => propSatisfies(includes(tag), 'tags')
const filterByTag = tag => filter(tagsContain(tag), data)
console.log(filterByTag('Silliness'))

CodePudding user response:

You can use guard for the 'All' value to return all values and regular filter to filter array by tag.

const data = [{"id":"card1","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","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","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","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."}];

const filterByTag = (arr, tag) => {
  if (tag === 'All') return arr;
  return arr.filter(({ tags }) => tags.includes(tag));
};

console.log(filterByTag(data, 'Design'));
.as-console-wrapper{min-height: 100%!important; top: 0}

  • Related