Search code examples
reactjsarraysobjectfilter

How to create an array from a Obj in another array? JS React


I want to build a self updating filter with checkboxes.

My Data:


const Shooting= [
    {
      name: "John & Johna ",
      tag: ["wedding", "couple"],
      img: [ src1 , src2, ...] //irrelevant
    },
    {
      name: "Mario & Marie",
      tag: ["couple", "NSFW"],
      img: [ src1 , src2, ...] //irrelevant
    },
  ];
  export default Shooting;

how my output should look like that:

Filter:
[]wedding 
[]couple  
[]NSFW    
// [] are checkboxes, "couple" is a duplicate in the array

My code idea:

  1. Get all tags into a new array
  2. Build function to remove duplicates from new array
  3. list the filtered array with map-function -> Obj.map((tag))=>{...}

My question:

How can I get all tags in a new list?


Solution

  • You can try with [...new Set(Shooting.map(({ tag }) => tag).flat(1))],

    -> Shooting.map(({tag}) => tag) will give back the tags in array.

    -> Then we can use array.flat() to concatenate the tags.

    -> Then to remove duplicate, we use ...new Set(...) .

    const App = () => {
      const Shooting = [
        {
          name: "John & Johna ",
          tag: ["wedding", "couple"],
          img: ["src1", "src2"]
        },
        {
          name: "Mario & Marie",
          tag: ["couple", "NSFW"],
          img: ["src1", "src2"]
        }
      ];
    
      const result = [...new Set(Shooting.map(({ tag }) => tag).flat(1))];
    
    
      return <div> 
        <h2> Filter: </h2> 
        <ul>
          {
            result.map((list, i) => <div key={i}><input type="checkbox" /> {list} </div> )
          }
        </ul> 
       </div>
    }
    
    
    // Render it
    ReactDOM.createRoot(
        document.getElementById("root")
    ).render(
        <App  />
    );
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>