programing

개체 키 배열 가져오기

bestcode 2022. 9. 25. 00:28
반응형

개체 키 배열 가져오기

JavaScript 객체의 키를 jQuery 또는 순수 JavaScript 중 하나로 배열하고 싶습니다.

이것보다 덜 장황한 방법은 없을까?

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
    keys.push(key);
}

사용방법:

var foo = {
  'alpha': 'puffin',
  'beta': 'beagle'
};

var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta'] 
// (or maybe some other order, keys are unordered).

이것은 ES5 기능입니다.즉, 최신 브라우저에서는 모두 동작하지만 레거시 브라우저에서는 동작하지 않습니다.

ES5-shim에는 훔칠있는 기능이 있습니다.

jQuery's 를 사용할 수 있습니다.

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' },
keys = $.map(foo, function(v, i){
  return i;
});

물론, Object.keys() 최고의 방법은 객체의 키를 가져.만약 그것이 당신의 환경에서 사용할 수 없습니다, 그것 빼고 고려해야 할 필요한 건 하찮게와 같은 예처럼 코드를 사용하는 shimmed 당신의 루프의 시제품을 사슬 모든 속성을, 과 달리 반복할 것이달 수 있다.Object.keys()의 동작).

하지만, 당신의 예제 코드는...

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
    keys.push(key);
}

jsFiddle.

...수정될 수 있습니다.가변 부분에서 제대로 할당할 수 있습니다.

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [], i = 0;
for (keys[i++] in foo) {}

jsFiddle.

물론, 이 동작은 다른 것들과 다릅니다.Object.keys()실제로(jsFiddle)는 않는다.여러분은 단지 MDN 문서화를 심을 사용할 수 있다.

n-depth 네스트된 객체의 키를 플랫 배열로 나열할 것을 찾고 있는 경우:

const getObjectKeys = (obj, prefix = '') => {
  return Object.entries(obj).reduce((collector, [key, val]) => {
    const newKeys = [ ...collector, prefix ? `${prefix}.${key}` : key ]
    if (Object.prototype.toString.call(val) === '[object Object]') {
      const newPrefix = prefix ? `${prefix}.${key}` : key
      const otherKeys = getObjectKeys(val, newPrefix)
      return [ ...newKeys, ...otherKeys ]
    }
    return newKeys
  }, [])
}

console.log(getObjectKeys({a: 1, b: 2, c: { d: 3, e: { f: 4 }}}))

덜 장황한 것은 잘 모르겠지만, 한 줄의 요청에 의해 다음 내용을 한 줄에 강요하게 되었습니다.그러나 피토닉이 얼마나 심한지는 모릅니다.

var keys = (function(o){var ks=[]; for(var k in o) ks.push(k); return ks})(foo);

요약

오브젝트의 모든 키를 취득하기 위해 사용할 수 있는Object.keys().Object.keys()는 개체를 인수로 받아 모든 키의 배열을 반환합니다.

예:

const object = {
  a: 'string1',
  b: 42,
  c: 34
};

const keys = Object.keys(object)

console.log(keys);

console.log(keys.length) // we can easily access the total amount of properties the object has

위의 예에서는 키 const에 키 배열을 저장합니다.그런 다음 키 배열의 길이를 확인함으로써 개체 속성의 양에 쉽게 액세스할 수 있습니다.

값을 취득하는 방법Object.values()

상보적 기능Object.keys()Object.values()이 함수는 개체를 인수로 사용하여 값의 배열을 반환합니다.예를 들어 다음과 같습니다.

const object = {
  a: 'random',
  b: 22,
  c: true
};


console.log(Object.values(object));

Underscore.js를 사용하기로 결정했다면 사용하는 것이 좋습니다.

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
_.each( foo, function( val, key ) {
    keys.push(key);
});
console.log(keys);

2022년과 JavaScript는 여전히 해시를 사용하는 건전한 방식을 가지고 있지 않다.

이는 경고를 발생시키지만 다음과 같이 작동합니다.

Object.prototype.keys = function() { return Object.keys(this) }
console.log("Keys of an object: ", { a:1, b:2 }.keys() )

// Keys of an object:  Array [ "a", "b" ]
// WARN: Line 8:1:  Object prototype is read only, properties should not be added  no-extend-native

, 빌트인 오브젝트의 확장은 논란의 여지가 있습니다.

언급URL : https://stackoverflow.com/questions/8763125/get-array-of-objects-keys

반응형