Home > Software engineering >  How to filter Object with multiple keys inside
How to filter Object with multiple keys inside

Time:03-20

I'm a beginner. Imagine data being like this on a js file :

const myData = {
  1: {
    1: {
      displayText: "word1",
      text: "worddisplay1",
    },
    2: {
      displayText: "word1",
      text: "worddisplay1",
    },
    3: {
     displayText: "word3",
      text: "worddisplay3",
    }
  },
 2: {
    1: {
      displayText: "word4",
      text: "worddisplay4",
    },
    2: {
      displayText: "word5",
      text: "worddisplay5",
    },
    3: {
     displayText: "word6",
      text: "worddisplay6",
    }
  }
}

I would like to do a search filter in this data, in javascript.

For example, if i enter the word "display1", it will give me all the results containing the word "display1".

I tried like this :

 Object.keys(myData).forEach((k) => {
      console.log(k, myData[k]);
    });

But i don't know what I have to do after, should I use a forEach inside a forEach? I know I have to use the "includes" keyword.

If someone can bring me the trick, i'm being stuck for days

CodePudding user response:

try this.


Object.values(myData)
  .flatMap(it => Object.values(it))
  .filter(it => it.displayText.includes('word1'));

  • Related