admin管理员组

文章数量:1297247

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);
        }
    });
    

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);
        }
    });
    
Share Improve this question edited Jan 30, 2016 at 10:09 Daedalus asked Jan 30, 2016 at 8:49 DaedalusDaedalus 3051 gold badge6 silver badges15 bronze badges 18
  • So, iterate over values and check if one equals to it. – zerkms Commented Jan 30, 2016 at 8:51
  • @zerkms yes. I was just wondering if there was already an existing method – Daedalus Commented Jan 30, 2016 at 8:52
  • 1 @CakeToppings Considering, that the value of a property could be a primitive, another object or a function, a method checking for a value wouldn't be very useful. – Teemu Commented Jan 30, 2016 at 8:54
  • 1 @CakeToppings your last comment has made your question very different then what it asks currently. What you want is to search through an array of cars (or just an object and checking its keys), and checking if there is no null or undefined or even '' (empty string) value – KarelG Commented Jan 30, 2016 at 9:05
  • 2 can you provide sample input and expected output what you want? – Grundy Commented Jan 30, 2016 at 9:10
 |  Show 13 more comments

5 Answers 5

Reset to default 15

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.

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>

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>');

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));
    }

本文标签: nodejsJavascript if a value exists in an objectStack Overflow