Benk I
Benk I

Reputation: 199

How to check a string is present in an object or not in js?

Note: OP is asking how to improve their working code

I want to check a string.substring(1) is present in an object or not. If it presents then return it from the object or else return empty. I have written the below pseudo code.

For example, if my string is *Test Title, I want to check this string without the first letter i.e. string.substring(1) is present in the given object with array value title here it is present. So we need to return Test Title. If I pass *Test1 since it is not present with title it should return ''

let string = '*Test Title'

let string1 = '*Test1'

let object = {
    "0": [
        "para",
        "WZYYoPd3ummvxQN0"
    ],
    "1": [
        "insertorder",
        "first"
    ],
    "2": [
        "lmkr",
        "1"
    ],
    "3": [
        "title",
        "Test Title"
    ],
    "4": [
        "para",
        "Test1"
    ],
}

const b = Object.entries(object)
  .filter(value => value[1])
let str = ''
const c = b.filter(a => a[1][0] === 'title')
if (c.length) {
  c.filter((key) => {
    key[1].filter((n) => {
      if (n != 'title' && n === string.substring(1)) {
        str = n;
      }
    })
  })
}
if (str === '') {
  console.log(string);
} else {
  console.log(str);
}

The code works correctly. I want to know is there any room for simplifying this? Can anyone help me out?

Upvotes: 0

Views: 655

Answers (1)

AJ31
AJ31

Reputation: 258

If I understood it correctly, if the first element of the inside list is 'title' , then only you'll need to check for the string present. So you can try this :

let str = '';
for(var key in obj) {
    if(obj[key][0] === "title") {
        str = obj[key][1] === string.substring(1) ? obj[key][1] : '';
        break;
    }
}

Upvotes: 1

Related Questions