简体   繁体   English

如何使用 JavaScript 检查对象中是否存在值

[英]How to check if a value exists in an object using JavaScript

I have an object in JavaScript:我在 JavaScript 中有一个对象:

var obj = {
   "a": "test1",
   "b": "test2"
}

How do I check that test1 exists in the object as a value?如何检查对象中是否存在 test1 作为值?

You can turn the values of an Object into an array and test that a string is present.您可以将 Object 的值转换为数组并测试是否存在字符串。 It assumes that the Object is not nested and the string is an exact match:它假定 Object 没有嵌套并且字符串是完全匹配的:

var obj = { a: 'test1', b: 'test2' };
if (Object.values(obj).indexOf('test1') > -1) {
   console.log('has test1');
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

最短的 ES6+ 一个班轮:

let exists = Object.values(obj).includes("test1");

You can use the Array method .some :您可以使用 Array 方法.some

var exists = Object.keys(obj).some(function(k) {
    return obj[k] === "test1";
});

Try:尝试:

 var obj = { "a": "test1", "b": "test2" }; Object.keys(obj).forEach(function(key) { if (obj[key] == 'test1') { alert('exists'); } });

Or或者

 var obj = { "a": "test1", "b": "test2" }; var found = Object.keys(obj).filter(function(key) { return obj[key] === 'test1'; }); if (found.length) { alert('exists'); }

This will not work for NaN and -0 for those values.这不适用于NaN-0对于这些值。 You can use (instead of === ) what is new in ECMAScript 6:您可以使用(而不是=== )ECMAScript 6 中的新功能:

 Object.is(obj[key], value);

With modern browsers you can also use:使用现代浏览器,您还可以使用:

 var obj = { "a": "test1", "b": "test2" }; if (Object.values(obj).includes('test1')) { alert('exists'); }

Use a for...in loop:使用for...in循环:

for (let k in obj) {
    if (obj[k] === "test1") {
        return true;
    }
}

You can use Object.values() :您可以使用Object.values()

The Object.values() method returns an array of a given object's own enumerable property values, 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.values()方法返回给定对象自己的可枚举属性值的数组,其顺序与for...in循环提供的顺序相同(不同之处在于 for-in 循环枚举原型链中的属性以及)。

and then use the indexOf() method:然后使用indexOf()方法:

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. indexOf()方法返回可以在数组中找到给定元素的第一个索引,如果不存在则返回 -1。

For example:例如:

Object.values(obj).indexOf("test`") >= 0

A more verbose example is below:下面是一个更详细的示例:

 var obj = { "a": "test1", "b": "test2" } console.log(Object.values(obj).indexOf("test1")); // 0 console.log(Object.values(obj).indexOf("test2")); // 1 console.log(Object.values(obj).indexOf("test1") >= 0); // true console.log(Object.values(obj).indexOf("test2") >= 0); // true console.log(Object.values(obj).indexOf("test10")); // -1 console.log(Object.values(obj).indexOf("test10") >= 0); // false

For a one-liner, I would say:对于单线,我会说:

exist = Object.values(obj).includes("test1");
console.log(exist);

I did a test with all these examples, and I ran this in Node.js v8.11.2 .我对所有这些示例进行了测试,并在Node.js v8.11.2中运行了它。 Take this as a guide to select your best choice.以此为指导来选择您的最佳选择。

 let i, tt; const obj = { a: 'test1', b: 'test2', c: 'test3', d: 'test4', e: 'test5', f: 'test6' }; console.time("test1") i = 0; for( ; i<1000000; i=i+1) { if (Object.values(obj).indexOf('test4') > -1) { tt = true; } } console.timeEnd("test1") console.time("test1.1") i = 0; for( ; i<1000000 ; i=i+1) { if (~Object.values(obj).indexOf('test4')) { tt = true; } } console.timeEnd("test1.1") console.time("test2") i = 0; for( ; i<1000000; i=i+1) { if (Object.values(obj).includes('test4')) { tt = true; } } console.timeEnd("test2") console.time("test3") i = 0; for( ; i<1000000 ; i=i+1) { for(const item in obj) { if(obj[item] == 'test4') { tt = true; break; } } } console.timeEnd("test3") console.time("test3.1") i = 0; for( ; i<1000000; i=i+1) { for(const [item, value] in obj) { if(value == 'test4') { tt = true; break; } } } console.timeEnd("test3.1") console.time("test4") i = 0; for( ; i<1000000; i=i+1) { tt = Object.values(obj).some((val, val2) => { return val == "test4" }); } console.timeEnd("test4") console.time("test5") i = 0; for( ; i<1000000; i=i+1) { const arr = Object.keys(obj); const len = arr.length; let i2 = 0; for( ; i2<len ; i2=i2+1) { if(obj[arr[i2]] == "test4") { tt = true; break; } } } console.timeEnd("test5")

Output on my server在我的服务器上输出

test1:   272.325 ms
test1.1: 246.316 ms
test2:   251.98 0ms
test3:    73.284 ms
test3.1: 102.029 ms
test4:   339.299 ms
test5:    85.527 ms
if (Object.values(obj).includes('test1')){
   return true
}

you can try this one你可以试试这个

var obj = {
  "a": "test1",
  "b": "test2"
};

const findSpecificStr = (obj, str) => {
  return Object.values(obj).includes(str);
}

findSpecificStr(obj, 'test1');

You can try this:你可以试试这个:

function checkIfExistingValue(obj, key, value) {
    return obj.hasOwnProperty(key) && obj[key] === value;
}
var test = [{name : "jack", sex: F}, {name: "joe", sex: M}]
console.log(test.some(function(person) { return checkIfExistingValue(person, "name", "jack"); }));

In new version if ecma script now we can check vslues by ?.在新版本中,如果 ecma 脚本现在我们可以通过?. operations..操作..

Its so simpler and easy yo check values in a object or nested or objects它是如此简单易行哟检查对象或嵌套或对象中的值

var obj = {
   "a": "test1",
   "b": "test2"
}

if(obj?.a) return "i got the value"

Similarly since in Javascript most used primitive type is Object同样,因为在 Javascript 中最常用的原始类型是 Object

We can use this arrays, functions etc too我们也可以使用这个数组、函数等

aFunc = () => { return "gotcha"; }

aFunc?.() // returns gotcha

myArray = [1,2,3]

myArray?.[3] // returns undefined

Thanks谢谢

Best way to find value exists in an Object using Object.keys()使用 Object.keys() 在对象中查找值的最佳方法

obj = {
 "India" : {
 "Karnataka" : ["Bangalore", "Mysore"],
 "Maharashtra" : ["Mumbai", "Pune"]
 },
 "USA" : {
 "Texas" : ["Dallas", "Houston"],
 "IL" : ["Chicago", "Aurora", "Pune"]
 }
}

function nameCity(e){
    var finalAns = []
    var ans = [];
    ans = Object.keys(e).forEach((a)=>{
        for(var c in e[a]){
            e[a][c].forEach(v=>{
                if(v === "Pune"){
                    finalAns.push(c)
                }
            })

        }
    })
    console.log(finalAns)
}


nameCity(obj)
var obj = {"a": "test1", "b": "test2"};
var getValuesOfObject = Object.values(obj)
for(index = 0; index < getValuesOfObject.length; index++){
    return Boolean(getValuesOfObject[index] === "test1")
}

The Object.values() method returned an array (assigned to getValuesOfObject) containing the given object's (obj) own enumerable property values. Object.values() 方法返回一个数组(分配给 getValuesOfObject),其中包含给定对象 (obj) 自己的可枚举属性值。 The array was iterated using the for loop to retrieve each value (values in the getValuesfromObject) and returns a Boolean() function to find out if the expression ("text1" is a value in the looping array) is true.使用for循环对数组进行迭代以检索每个值(getValuesfromObject 中的值)并返回一个 Boolean() 函数以确定表达式(“text1”是循环数组中的值)是否为真。

getValue = function (object, key) {
    return key.split(".").reduce(function (obj, val) {
        return (typeof obj == "undefined" || obj === null || obj === "") ? obj : (_.isString(obj[val]) ? obj[val].trim() : obj[val]);}, object);
};

var obj = {
   "a": "test1",
   "b": "test2"
};

Function called:调用函数:

 getValue(obj, "a");

For complex structures, here is how I do it:对于复杂的结构,我是这样做的:

 const obj = { test: [{t: 't'}, {t1: 't1'}, {t2: 't2'}], rest: [{r: 'r'}, {r1: 'r1'}, {r2: 'r2'}] } console.log(JSON.stringify(obj).includes(JSON.stringify({r1: 'r1'}))) // returns true console.log(JSON.stringify(obj).includes(JSON.stringify({r1: 'r2'}))) // returns false

_.has() method is used to check whether the path is a direct property of the object or not. _.has()方法用于检查路径是否是对象的直接属性。 It returns true if the path exists, else it returns false.如果路径存在则返回真,否则返回假。

 var object = { 'a': { 'b': 2 } }; console.log(_.has(object, 'a.b')); console.log(_.has(object, ['a','b'])); console.log(_.has(object, ['a','b','c']));

Output: true true false输出:真真假

if( myObj.hasOwnProperty('key') && myObj['key'] === value ){
    ...
}

The simple answer to this is given below.下面给出了简单的答案。

This is working because every JavaScript type has a “constructor” property on it prototype ”.这是有效的,因为每个 JavaScript 类型在它的原型上都有一个“构造函数”属性。

let array = []
array.constructor === Array
// => true


let data = {}
data.constructor === Object
// => true

This should be a simple check.这应该是一个简单的检查。

Example 1示例 1

var myObj = {"a": "test1"}

if(myObj.a == "test1") {
    alert("test1 exists!");
}

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

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