Home > Net >  How to check whether a specific string occurs as a value in an object?
How to check whether a specific string occurs as a value in an object?

Time:09-17

I have an object that is structured like this (simplified version):

{
  "customConfig": {
    "homepage": {
      "url": "path/to/homepage",
      "base_path": "www.stackoverflow.com"
    },
    "portfolio": {
      "url": "path/to/portfolio",
      "base_path": "www.github.com"
    },
    "moreStuff": {
        //...
    }
}

Now I want to check whether a specific string value (in my case for the key base_path) exists.

So how can I check whether, for example, the string www.github.com exists in my customConfig object for the key base_path?

A boolean return value would be enough here.

CodePudding user response:

The OP needs to utilize Object.values in order to retrieve an array of all the config object's property values. Then the OP wants to know if some condition like such a value's/item's base_path value equals a certain address.

console.log(
  "does object contain an item where `base_path` equals 'www.github.com' ?",
  Object.values({
      "homepage": {
        "url": "path/to/homepage",
        "base_path": "www.stackoverflow.com"
      },
      "portfolio": {
        "url": "path/to/portfolio",
        "base_path": "www.github.com"
      },
      "moreStuff": {
          //...
      }
    }).some(item => item.base_path === 'www.github.com')
);

CodePudding user response:

You can try something like

let obj = {
  "customConfig": {
    "homepage": {
      "url": "path/to/homepage",
      "base_path": "www.stackoverflow.com"
    },
    "portfolio": {
      "url": "path/to/portfolio",
      "base_path": "www.github.com"
    }
    }
}

let exist = Object.keys(obj.customConfig).filter(page => obj.customConfig[page]['base_path'] == 'www.github.com').length>0;

console.log(exist);

CodePudding user response:

Iterative looping in case property value is array or object.

Object.values(obj) will turn arrary and object values in a array of values where we can iterate over the values

let data = {
    "customConfig": {
        "homepage": {
            "url": "path/to/homepage",
            "base_path": "www.stackoverflow.com"
        },
        "portfolio": {
            "url": "path/to/portfolio",
            "base_path": "www.github.com"
        }
    }
}
// self recursive function loop 
let hasValue = (obj, value) => {
  return   Object.values(obj).some(s => {
        if (s === value) {
            return true;
        }
        if (typeof s === 'object' || Array.isArray(s)) {
            return hasValue(s, value);

        }
        return false;
    });
}

console.log(hasValue(data, "www.stackoverflow.com"));

CodePudding user response:

To check whether some value exists in customConfig object based on key of customConfig.

let data = {
  "customConfig": {
    "homepage": {
      "url": "path/to/homepage",
      "base_path": "www.stackoverflow.com"
    },
    "portfolio": {
      "url": "/to/portfolio",
      "base_path": "www.github.com"
    }
  }
};

// create array for url and base_path; which will simplify to search based on key
const result = Object.keys(data.customConfig).reduce((acc, key) =>{
  const {url, base_path} = data.customConfig[key];
  acc['url'].push(url);
  acc['base_path'].push(base_path);
  return acc; 
} , {url:[], base_path: []});

//to search in url
const x = result['url'].includes('/to/portfolio');
console.log(x);

//to search in basepath
const y= result['base_path'].includes('www.stackoverflow.com');
console.log(y);

CodePudding user response:

You could use a recursive function.

To find a certain key, call hasOwnProperty (or use includes on Object.keys) at each nesting level to see if the key is found there.

To find a certain value, use includes on Object.values().

To find a key/value pair, find the key (as above) and verify that the value for that key is the searched value:

const containsKey = (obj, key) => Object(obj) === obj && (
    obj.hasOwnProperty(key) ||
    Object.values(obj).some(child => containsKey(child, key))
); 

const containsValue = (obj, value) => Object(obj) === obj && ( 
    Object.values(obj).includes(value) ||
    Object.values(obj).some(child => containsValue(child, value))
); 

const containsKeyValue = (obj, key, value) => Object(obj) === obj && (
    obj.hasOwnProperty(key) && obj[key] === value ||
    Object.values(obj).some(child => containsKeyValue(child, key, value))
); 

// Example run:
let data = {
  "customConfig": {
    "homepage": {
      "url": "path/to/homepage",
      "base_path": "www.stackoverflow.com"
    },
    "portfolio": {
      "url": "path/to/portfolio",
      "base_path": "www.github.com"
    },
    "moreStuff": {
        //...
    }
  }
};

console.log(containsKey(data, "base_path")); // true
console.log(containsValue(data, "www.github.com")); // true
console.log(containsKeyValue(data, "base_path", "www.github.com")); // true

CodePudding user response:

I solved it like this (simplified) :)

const specificValueExists = (url: string): boolean => {
    return Object.values(myObject).indexOf(url) > -1;
);

Thanks for all suggested solutions.

CodePudding user response:

A regular expression could be of use here:

const x = {
  "customConfig": {
    "homepage": {
      "url": "path/to/homepage",
      "base_path": "www.stackoverflow.com"
    },
    "portfolio": {
      "url": "path/to/portfolio",
      "base_path": "www.github.com"
    },
    "moreStuff": {
        //...
    }
  }
  }

const regex = /base_path\":"www\.github\.com/

const t = regex.test(JSON.stringify(x.customConfig))

console.log(t)

  • Related