javascript 检查对象是否在javascript中具有一组属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20578679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:48:43  来源:igfitidea点击:

Check if object has a set of properties in javascript

javascriptjqueryobjectpropertiesoperators

提问by Ben

Let's say I have an object named a, how could I check that ahas a specific list of multiple properties in shorthand, I think it can be done using inlogical operator,

比方说,我有一个名为对象a,我怎么能检查a在速记多个属性的具体名单,我认为这是可以做到用逻辑运算符,

Something like this:

像这样的东西:

var a = {prop1:{},prop2:{},prop3:{}};
if ({1:"prop1",2:"prop2",3:"prop3"} in a)
    console.log("a has these properties:'prop1, prop2 and prop3'");

EDIT

编辑

If plain javascript can't help, jQuery will do, but i prefer javascript

如果普通的 javascript 无济于事,jQuery 可以,但我更喜欢 javascript

EDIT2

编辑2

Portability is the privilege

便携性是特权

回答by p.s.w.g

The simplest away is to use a conventional &&:

最简单的方法是使用传统的&&

if ("prop1" in a && "prop2" in a && "prop3" in a) 
    console.log("a has these properties:'prop1, prop2 and prop3'");

This isn't a 'shorthand', but it's not that much longer than what you've proposed.

这不是“速记”,但它并没有比您提出的长多少。

You can also place the property names you want to test in an array and use the everymethod:

您还可以将要测试的属性名称放在数组中并使用以下every方法:

var propertiesToTest = ["prop1", "prop2", "prop3"];
if (propertiesToTest.every(function(x) { return x in a; })) 
    console.log("a has these properties:'prop1, prop2 and prop3'");

Note however, that this was introduced in ECMAScript 5, so it is not available on some older browsers. If this is a concern, you can provide your own version of it. Here's the implementation from MDN:

但是请注意,这是在 ECMAScript 5 中引入的,因此在某些较旧的浏览器上不可用。如果这是一个问题,您可以提供您自己的版本。这是 MDN 的实现:

if (!Array.prototype.every) {
  Array.prototype.every = function(fun /*, thisp */) {
    'use strict';
    var t, len, i, thisp;

    if (this == null) {
      throw new TypeError();
    }

    t = Object(this);
    len = t.length >>> 0;
    if (typeof fun !== 'function') {
        throw new TypeError();
    }

    thisp = arguments[1];
    for (i = 0; i < len; i++) {
      if (i in t && !fun.call(thisp, t[i], i, t)) {
        return false;
      }
    }

    return true;
  };
}

回答by Dexygen

This is where the underscore.js libraryreally shines. For instance it provides an already poly-filled every()method as suggested in a comment to p.s.w.g.'s answer: http://underscorejs.org/#every

这是underscore.js 库真正闪耀的地方。例如,它提供了一个已经填充的every()方法,如对 pswg 答案的评论中所建议的:http://underscorejs.org/#every

But there's more than one way to do it; the following, while more verbose, may also suit your needs, and exposes you to more of what underscore can do (e.g. _.keys and _.intersection)

但是有不止一种方法可以做到;以下虽然更冗长,但也可能适合您的需求,并让您了解下划线可以做的更多事情(例如 _.keys 和 _.intersection)

var a = {prop1:{},prop2:{},prop3:{}};
var requiredProps = ['prop1', 'prop2', 'prop3'];
var inBoth = _.intersection(_.keys(a), requiredProps);
if (inBoth.length === requiredProps.length) {
    //code
}

回答by sachinjain024

Use Array.reducelike this:

像这样使用Array.reduce

var testProps = ['prop1', 'prop2', 'prop3'];
var a = {prop1:{},prop2:{},prop3:{}};

var result = testProps.reduce(function(i,j) { return i && j in a }, true);
console.log(result);

回答by StackSlave

Like this:

像这样:

var testProps = ['prop1', 'prop2', 'prop3', 'prop4'];
var num = -1, outA;
for(var i in a){
  if(i === testProps[++num])outA[num] = i;
}
console.log('properties in a: '+outA.join(', '));

回答by Ringo

I think it's good to try it:

我觉得可以试试:

/* Create an object class */
var obj = function(){ this.attributes = new Array(); }
obj.prototype.addProp = function(value){ this.attributes.push(new attribute(value)); }
obj.prototype.hasProp = function(value){ 
    for(var i = 0; i < this.attributes.length; i++){ 
      if(value == this.attributes[i].value) return true; } return false; }
function attribute(value){
    this.value = value;
}
/* Testing object has some value*/
var ob = new obj();
ob.addProp('1');
ob.addProp('2');
ob.addProp('3');
 //* check value index
//alert(ob.attributes[0].value);
 //* check if ob has prop
alert(ob.hasProp('1'));

Here is DEMO

这是演示

回答by Mark Tyers

Slightly more elegant use of the Object.every()prototype function to include try-catch:

稍微优雅地使用Object.every()原型函数来包括try-catch

try {
  const required = ['prop1', 'prop2', 'prop3']
  const data = {prop1: 'hello', prop2: 'world', prop3: 'bad'}
  if (!required.every( x => x in data )) throw new Error('missing property')
  console.log('all properties found')
} catch(err) {
  console.log(err.message)
}
``