0
my_arr = [
  { "keywords": "set,on,increease,decrease,low,medium,high,forward,backward", "commands": "SET" },
  { "keywords": "get,access,retrieve", "commands": "GET" },
  { "keywords": "run", "commands": "RUN" },
  { "keywords": "stop", "commands": "STOP" }
]

i want to find if increase exists in keywords?

5

2 Answers 2

0

What about something like this

const data = [
  { "keywords": "set,on,increase,decrease,low,medium,high,forward,backward", "commands": "SET" },
  { "keywords": "get,access,retrieve", "commands": "GET" },
  { "keywords": "run", "commands": "RUN" },
  { "keywords": "stop", "commands": "STOP" }
]


const keywordExists = keyword => data.flatMap(({keywords}) => keywords.split(',')).includes(keyword)


console.log(keywordExists('increase'))
console.log(keywordExists('decrease'))
console.log(keywordExists('not valid keyword'))

Sign up to request clarification or add additional context in comments.

2 Comments

hi this is fine how about if i find increase then i get the whole object as output something like this { "keywords": "set,on,increase,decrease,low,medium,high,forward,backward", "commands": "SET" }
@telus you just have to replace flatMap with find
-1

I think this must be work.

const keys = [
  { "keywords": "set,on,increease,decrease,low,medium,high,forward,backward", "commands": "SET" },
  { "keywords": "get,access,retrieve", "commands": "GET" },
  { "keywords": "run", "commands": "RUN" },
  { "keywords": "stop", "commands": "STOP" }
]

function check(value) {
    // On every value on keys get index
    for (let i in keys) {
        // Get key from keys with index value
        const key = keys[i];
        // Check if is matching
        if (key.keywords.split(',').includes(value))
            // If successfuly matching is found return commands value
            return key.commands;
    }
    // If any result doesnt returned, return null.
    return null;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.