Home > Blockchain >  I am trying to only return items in an array that contain a matching key with a true value where the
I am trying to only return items in an array that contain a matching key with a true value where the

Time:08-18

Brief example:

piece of state: ['youth', 'college'];

event Object:

{ name: theEvent,
ageDivisions: {
    youth: true,
    middleSchool: true,
    highSchool: true,
    college: true
    open: false
},
}

What I want to accomplish

I want to filter through multiple event objects and only return when the event at least contains all the matching strings in the state array. this array is created based on what the user selects from the form (image Below)

Form User Fills Out

My approach so far:

So far my approach has been to turn the events age divisions parameter into an array of arrays that contain the key and the value. Positions 1 and 2 respectfully

Here is the code:

codePenLink

if (filterParamaters.ageDivisions !== undefined && filterParamaters.ageDivisions.length != false) {


          let parsedEvents = events.data.map(({ attributes: event }) => {
            return {
              ...event,
              ...event.attributes,
              ageDivisions: JSON.parse(event.ageDivisions),
              eventStyles: JSON.parse(event.eventStyles),
            }
          })
          console.log({ parsedEvents });

          filteredEventss = parsedEvents.filter((event) => {
            // make event .attributes.ageDivisions object an array of key value pairs
            console.log({ eventThatWeAreFiltering: event });
            if ((event.ageDivisions !== undefined && event.ageDivisions !== null)) {
              let eventAgeDivisions = Object.entries(event.ageDivisions);
              console.log({ theAgifiedObject: eventAgeDivisions });
              // This maps through each object in the Object key value pair Array 
              // It might be easier to use map and just chang the array to only have the matching values
              let onlyTrueEventAgedivisions = eventAgeDivisions.map((ageDivision, index) => {
                console.log({ theAgeDivision: ageDivision[2] });
                if (ageDivision[2] === true) {
                  return [ageDivision[0], ageDivision[2]];
                } else {
                  return false;
                }
              })
              console.log({ theTrueEventAgedivisions: onlyTrueEventAgedivisions });
              
            }
          })
          console.log({ theFinishedFilteredevents: filteredEventss });
        }


 

CodePudding user response:

What I did was check if the ageDivisions existed in each object and if it does, run this filterParameters.ageDivisions list, checking if every property that you want to be true is set to true .

const result = parsedEvents.filter((e) => e.ageDivisions && filterParameters.ageDivisions.every(prop => e.ageDivisions[prop]))
console.log(result);
  • Related