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);
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
The code works correctly. I want to know is there any room for simplifying this? Can anyone help me out?
CodePudding user response:
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;
}
}