简体   繁体   中英

Javascript if a value exists in an object?

ive got an object:

var car = {
    company: "Honda",
    year: "2011",
    Model: "Brio"
}

I was wondering if there exists an inherited method (is that the right phrase?) to check if a value exists inside a given object, somewhat like x.hasOwnProperty , or if (x in car) . Or, should I write my own.

I've done a few google searches, but they all either lead to hasOwnProperty or to check if a value exists inside an array.

Editing to please all the people in the comments: There are two use cases i could think of where this would be useful:

  1. checking for undefined keys and reporting which one

    if (!car.isInvalid(car, undefined)) validCarsArray.push (car);
  2. Checking if a general user input exists in an object

    var text = searchBox.input; validCarArrays.forEach (function (car) { if (car.hasOwnValue(car, text)) { displayToUserAsResult (car); } });

Let's say we start with

const obj = {foo : "bar"};

Check for a value:

const hasValue = Object.values(obj).includes("bar");

Check for a property:

// NOTE: Requires obj.toString() if key is a number
const hasProperty = Object.keys(obj).includes("foo");

Multi-level value:

function hasValueDeep(json, findValue) {
    const values = Object.values(json);
    let hasValue = values.includes(findValue);
    values.forEach(function(value) {
        if (typeof value === "object") {
            hasValue = hasValue || hasValueDeep(value, findValue);
        }
    })
    return hasValue;
}

Multi-level property:

function hasPropertyDeep(json, findProperty) {
    const keys = Object.keys(json);
    let hasProperty = keys.includes((findProperty).toString());
    keys.forEach(function(key) {
        const value = json[key];
        if (typeof value === "object") {
            hasProperty = hasProperty || hasPropertyDeep(value, findProperty);
        }
    })
    return hasProperty;
}

No, there is no built in method to search for a value on an object.

The only way to do so is to iterate over all the keys of the object and check each value. Using techniques that would work even in old browsers, you can do this:

function findValue(o, value) {
    for (var prop in o) {
        if (o.hasOwnProperty(prop) && o[prop] === value) {
            return prop;
        }
    }
    return null;
}

findValue(car, "2011");    // will return "year"
findValue(car, "2012");    // will return null

Note: This will return the first property that contains the search value even though there could be more than one property that matched. At the cost of efficiency, you could return an array of all properties that contain the desired value.

Note: This uses the extra .hasOwnProperty() check as a safeguard against any code that adds enumerable properties to Object.prototype . If there is no such code and you're sure there never will be, then the .hasOwnProperty() check can be eliminated.

This function uses Object.keys() and returns an array with the keys for the object which has the given value.

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for ... in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

 var car = { company: "Honda", year: "2011", Model: "Brio" }; function getKeysWithValue(v, o) { return Object.keys(o).filter(function (k) { return o[k] === v; }); } document.write('<pre>' + JSON.stringify(getKeysWithValue('Honda', car), 0, 4) + '</pre>');

There is no built-in function but it can be done using Object.keys() and [].some() :

 function hasValue(obj, value) { return Object.keys(obj).some((key) => obj[key] == value); } var car = { company: "Honda", year: "2011", Model: "Brio" } snippet.log('car has Honda: ' + hasValue(car, 'Honda')); snippet.log('car has NotHonda: ' + hasValue(car, 'NotHonda'));
 <script src="https://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

I used this function, to check wether or not array2 contains a common value with array1.

const array1 = ['a','b','c','x'];
const array2 = ['z','y','x'];


function ContainsCommonItem3(arr1, arr2){
        return arr1.some(item => arr2.includes(item));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM