简体   繁体   English

Javascript 如果值存在于对象中?

[英]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) .我想知道是否存在一个继承的方法(这是正确的短语吗?)来检查给定对象中是否存在一个值,有点像x.hasOwnProperty ,或者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.我已经做了一些谷歌搜索,但它们都会导致hasOwnProperty或检查数组中是否存在值。

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 .注意:这使用额外的.hasOwnProperty()检查作为防止任何将可枚举属性添加到Object.prototype代码的保护措施。 If there is no such code and you're sure there never will be, then the .hasOwnProperty() check can be eliminated.如果没有这样的代码并且您确定永远不会有,那么可以取消.hasOwnProperty()检查。

This function uses Object.keys() and returns an array with the keys for the object which has the given value.该函数使用Object.keys()并返回与其中具有给定值的对象的按键阵列。

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). Object.keys()方法返回给定对象自己的可枚举属性的数组,其顺序与for ... in循环提供的顺序相同(区别在于 for-in 循环将原型链中的属性枚举为好)。

 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() :没有内置函数,但可以使用Object.keys()[].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.我使用这个函数来检查 array2 是否包含与 array1 的公共值。

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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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