Programing

JavaScript에 객체에 속성이 있는지 확인하는 방법은 무엇입니까?

lottogame 2020. 6. 14. 10:23
반응형

JavaScript에 객체에 속성이 있는지 확인하는 방법은 무엇입니까?


내가 선언한다고 가정

var ad = {}; 

이 객체에 사용자 정의 속성이 포함되는지 여부를 어떻게 확인할 수 있습니까?


다음과 같이 객체의 속성을 반복 할 수 있습니다.

for(var prop in ad) {
    if (ad.hasOwnProperty(prop)) {
        // handle prop as required
    }
}

hasOwnProperty()객체가 지정된 속성을 직접 속성으로 가지고 있고 객체의 프로토 타입 체인에서 상속되지 않는지 여부를 확인 하려면이 방법 을 사용하는 것이 중요합니다 .

편집하다

주석에서 : 해당 코드를 함수에 넣고 주석 이있는 부분에 도달하자마자 false를 반환하도록 할 수 있습니다

성능 테스트

속성을 테스트 할 때 Object.Keys 대 For..In 테스트


내장 Object.keys메소드를 사용하여 객체의 키 목록을 가져 와서 길이를 테스트 할 수 있습니다.

var x = {};
// some code where value of x changes and than you want to check whether it is null or some object with values

if(Object.keys(x).length > 0){
 // Your code here if x has some properties  
}

간단한 기능을 만드는 것은 어떻습니까?

function isEmptyObject(obj) {
  for(var prop in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
      return false;
    }
  }
  return true;
}

isEmptyObject({}); // true
isEmptyObject({foo:'bar'});  // false

hasOwnProperty직접 호출 하는 메소드 Object.prototype안전성을 조금만 높이는 것입니다 . 일반 obj.hasOwnProperty(...)호출을 사용하여 다음을 상상하십시오 .

isEmptyObject({hasOwnProperty:'boom'});  // false

주 : (미래에 대한) 위의 방법은에 의존 for...in문이 문은 반복 처리 열거 프로그래머가 아닌 열거 속성을 만들 수있는 방법이없는 현재 가장 널리 구현 인 ECMAScript 표준 (제 3 판)에서 속성을 .

그러나 이제 ECMAScript 5th Edition 에서 변경되었으며 열거 가능하지 않거나 쓰기 가능하지 않거나 삭제할 수없는 속성을 만들 수 있으므로 위의 방법 이 실패 할 수 있습니다 . 예 :

var obj = {};
Object.defineProperty(obj, 'test', { value: 'testVal', 
  enumerable: false,
  writable: true,
  configurable: true
});
isEmptyObject(obj); // true, wrong!!
obj.hasOwnProperty('test'); // true, the property exist!!

이 문제에 대한 ECMAScript 5 솔루션은 다음과 같습니다.

function isEmptyObject(obj) {
  return Object.getOwnPropertyNames(obj).length === 0;
}

The Object.getOwnPropertyNames method returns an Array containing the names of all the own properties of an object, enumerable or not, this method is being implemented now by browser vendors, it's already on the Chrome 5 Beta and the latest WebKit Nightly Builds.

Object.defineProperty is also available on those browsers and latest Firefox 3.7 Alpha releases.


With jQuery you can use:

$.isEmptyObject(obj); // Returns: Boolean

As of jQuery 1.4 this method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty).

With ECMAScript 5th Edition in modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

var obj = { blah: 1 };
var isEmpty = !Object.keys(obj).length;

Or plain old JavaScript:

var isEmpty = function(obj) {
               for(var p in obj){
                  return false;
               }
               return true;
            };

Most recent browsers (and node.js) support Object.keys() which returns an array with all the keys in your object literal so you could do the following:

var ad = {}; 
Object.keys(ad).length;//this will be 0 in this case

Browser Support: Firefox 4, Chrome 5, Internet Explorer 9, Opera 12, Safari 5

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


If you're using underscore.js then you can use the _.isEmpty function:

var obj = {};
var emptyObject = _.isEmpty(obj);

If you are willing to use lodash, you can use the some method.

_.some(obj) // returns true or false

See this small jsbin example


for (var hasProperties in ad) break;
if (hasProperties)
    ... // ad has properties

If you have to be safe and check for Object prototypes (these are added by certain libraries and not there by default):

var hasProperties = false;
for (var x in ad) {
    if (ad.hasOwnProperty(x)) {
        hasProperties = true;
        break;
    }
}
if (hasProperties)
    ... // ad has properties

for(var memberName in ad)
{
  //Member Name: memberName
  //Member Value: ad[memberName]
}

Member means Member property, member variable, whatever you want to call it >_>

The above code will return EVERYTHING, including toString... If you only want to see if the object's prototype has been extended:

var dummyObj = {};  
for(var memberName in ad)
{
  if(typeof(dummyObj[memberName]) == typeof(ad[memberName])) continue; //note A
  //Member Name: memberName
  //Member Value: ad[memberName]

}

Note A: We check to see if the dummy object's member has the same type as our testing object's member. If it is an extend, dummyobject's member type should be "undefined"


var hasAnyProps = false; for (var key in obj) { hasAnyProps = true; break; }
// as of this line hasAnyProps will show Boolean whether or not any iterable props exist

Simple, works in every browser, and even though it's technically a loop for all keys on the object it does NOT loop through them all...either there's 0 and the loop doesn't run or there is some and it breaks after the first one (because all we're checking is if there's ANY...so why continue?)


Very late answer, but this is how you could handle it with prototypes.

Array.prototype.Any = function(func) {
    return this.some(func || function(x) { return x });
}

Object.prototype.IsAny = function() {
    return Object.keys(this).Any();
}

When sure that the object is a user-defined one, the easiest way to determine if UDO is empty, would be the following code:

isEmpty=
/*b.b Troy III p.a.e*/
function(x,p){for(p in x)return!1;return!0};

Even though this method is (by nature) a deductive one, - it's the quickest, and fastest possible.

a={};
isEmpty(a) >> true

a.b=1
isEmpty(a) >> false 

p.s.: !don't use it on browser-defined objects.


Late answer, but some frameworks handle objects as enumerables. Therefore, bob.js can do it like this:

var objToTest = {};
var propertyCount = bob.collections.extend(objToTest).count();

You can use the following:

Double bang !! property lookup

var a = !![]; // true
var a = !!null; // false

hasOwnProperty This is something that I used to use:

var myObject = {
  name: 'John',
  address: null
};
if (myObject.hasOwnProperty('address')) { // true
  // do something if it exists.
}

However, JavaScript decided not to protect the method’s name, so it could be tampered with.

var myObject = {
  hasOwnProperty: 'I will populate it myself!'
};

prop in myObject

var myObject = {
  name: 'John',
  address: null,
  developer: false
};
'developer' in myObject; // true, remember it's looking for exists, not value.

typeof

if (typeof myObject.name !== 'undefined') {
  // do something
}

However, it doesn't check for null.

I think this is the best way.

in operator

var myObject = {
  name: 'John',
  address: null
};

if('name' in myObject) {
  console.log("Name exists in myObject");
}else{
  console.log("Name does not exist in myObject");
}

result:

Name exists in myObject

Here is a link that goes into more detail on the in operator: Determining if an object property exists

참고URL : https://stackoverflow.com/questions/2673121/how-to-check-if-object-has-any-properties-in-javascript

반응형