Sushant Rad
Sushant Rad

Reputation: 339

Find value in json if certain or all words matches to key of json

Suppose I have an json:

const apple ={"YABADABADU":"scoobydoo","somebody stop me":"mask","details":"somedetails","alpha":"romero"}

but sometimes it could be:

const apple = {"yabada":"scoobydoo", "somebody me" : "mask","details":"somedetails","alpha":"romero"}

It's just sample data based on certain extraction that will always contain, all or either part as, yabadabadu can be yabada , yaba , yabadabadu, YABADABADU and somebody stop me can be somebody, some, body.

For this I tried as

console.log(apple.includes('yaba').tolowercase())

But it's giving me error.

I just want to pass data to some other variable, let's say,

const banana = apple.yaba 
const mango = apple.some

and on

 console.log(banana) -> should give o/p "scoobydoo"
 console.log(mango) -> should give o/p "mask"

P.S. I want to set value for yaba and some , not for details and alpha

What could be the solution for this. If anyone need any further information , please let me know.

Upvotes: 1

Views: 126

Answers (2)

Michael Hoobler
Michael Hoobler

Reputation: 622

Here's a code sandbox that builds on Ran's answer: https://codesandbox.io/s/festive-hellman-o13nc?file=/src/index.js

The results is an array of keys you can use to access the data inside of apple

Upvotes: 1

Ran Turner
Ran Turner

Reputation: 18096

I would add an array which holds the possible prefixes.

Now, you can iterate through the key of the apple object and check if it contains one of the possible prefixes..

const apple ={"YABADABADU":"scoobydoo","somebody stop me":"mask"};

const possiblePrefix = ["yaba", "some", "body"]; //you can add here the rest of the posiible prefixes..

for (var key in apple){
   if (possiblePrefix.some(x => key.toLowerCase().includes(x))){
        console.log(apple[key]);
   }
}

Upvotes: 2

Related Questions