본문 바로가기

[JS] 객체 Object

[JS] 객체 Object

각기 다른 값을 가질 수 있지만, 입력해야 하는 데이터의 종류가 동일한 경우 객체를 사용하면 손쉽게 데이터를 관리할 수 있다.  (데이터끼리의 공통적인 속성을 가지는 경우) 

 

객체는 변수에 여러가지 정보가 담겨있을 때 적합한 자료구조이다.

 

 

 

bracket notation 키 값이 동적으로 변할 때, 키 값이 변수일 때 사용

(dot notation은 정해진 키 이름이 있을 때만 사용할 수 있기 때문에 한계가 있다.)

 

 

 

따옴표를 걷어낸 content가 키 값이 아닌 변수로 취급되고 있는 것. 따라서 참조 오류가 남.

Object.entries()

 

Object.entries() 메서드는 for...in와 같은 순서로 주어진 객체 자체의 enumerable 속성 [key, value] 쌍의 배열을 반환한다. (for-in 루프가 다른점은 프로토 타입 체인의 속성도 열거한다는 점이다).

Object.entries() 에 의해 반환된 배열(array)의 순서는 객체가 정의된 방법과 관련이 없다. 배열 순서가 쓸 곳이 있다면, 다음과 같이 정렬을 먼저 하시는 것이 좋다 Object.entries(obj).sort((a, b) => b[0].localeCompare(a[0]));.

 

const object1 = {
  a: 'somestring',
  b: 42
};

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

// Expected output:
// "a: somestring"
// "b: 42"

Syntax

Object.entries(obj)

Parameters

obj

객체 자체의 열거 가능한 문자열 키를 가진 속성 [key, value] 쌍이 반환되는 객체

Return value

지정된 객체 자체의 열거 가능한 문자속성 [key, value] 쌍의 배열

Description

Object.entries()는 object에 직접있는 enumerable 속성 [key, value] 쌍에 해당하는 배열을 반환한다. 속성의 순서는 개체의 속성 값을 수동으로 반복하여 주어진 순서와 동일하다.

Examples

const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

// array like object
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]

// array like object with random key ordering
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]

// getFoo is property which isn't enumerable
const myObj = Object.create({}, { getFoo: { value() { return this.foo; } } });
myObj.foo = 'bar';
console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]

// non-object argument will be coerced to an object
console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]

// returns an empty array for any primitive type, since primitives have no own properties
console.log(Object.entries(100)); // [ ]

// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}

// Or, using array extras
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
});

Converting an Object to a Map

new Map() 생성자는 반복 가능한 항목을 허용한다. Object.entries를 사용하면 Object에서 Map로 쉽게 변환 할 수 있다.

const obj = { foo: 'bar', baz: 42 };
const map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baz: 42 }

Iterating through an Object

Array Destructuring을 사용하면 객체를 쉽게 반복 할 수 있다.

const obj = { foo: 'bar', baz: 42 };
Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`)); // "foo: bar", "baz: 42"

Object.keys()

Object.keys() 메소드는 주어진 객체의 속성 이름들을 일반적인 반복문과 동일한 순서로 순회되는 열거할 수 있는 배열로 반환합니다.

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// Expected output: Array ["a", "b", "c"]

구문

Object.keys(obj)

매개변수

obj

열거할 수 있는 속성 이름들을 반환 받을 객체

반환 값

전달된 객체의 열거할 수 있는 모든 속성 이름들을 나타내는 문자열 배열

설명

Object.keys() 는 전달된 객체에서 직접 찾은 열거할 수 있는 속성 이름에 해당하는 문자열 배열을 반환한다. 속성 이름의 순서는 객체의 속성을 수동으로 반복하여 지정하는 것과 동일하다.

예시

Using Object.keys

// 단순 배열
const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// 배열형 객체
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

// 키와 순서가 무작위인 배열형 객체
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']

// getFoo 는 열거할 수 없는 속성입니다.
const myObj = Object.create({}, {
  getFoo: {
    value: function () { return this.foo; }
  }
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']

만약 열거할 수 없는 속성도 포함한 속성 이름들을 원한다면, 다음을 참고할 수 있다. Object.getOwnPropertyNames().

비객체 강제 형변환

ES5에서, 이 메서드의 인수에 비객체(원시형)을 전달할 경우, TypeError가 발생한다. ES2015부터는 객체가 아닌 인수는 객체로 강제 변환된다.

// ES5
Object.keys('foo');  // TypeError: "foo" is not an object

// ES2015+
Object.keys('foo');  // ["0", "1", "2"]
Copy to Clipboard

폴리필

Object.keys를 지원하지 않는 환경에서 사용하시려면 다음 스니펫을 복사하자.

// From https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
  Object.keys = (function() {
    'use strict';
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;

    return function(obj) {
      if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) {
        throw new TypeError('Object.keys called on non-object');
      }

      var result = [], prop, i;

      for (prop in obj) {
        if (hasOwnProperty.call(obj, prop)) {
          result.push(prop);
        }
      }

      if (hasDontEnumBug) {
        for (i = 0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) {
            result.push(dontEnums[i]);
          }
        }
      }
      return result;
    };
  }());
}
728x90

'FE > JavaScript' 카테고리의 다른 글

[코플릿/JS] 반복문 _ 소수찾기 & 소수 이어 붙이기 🤍  (0) 2023.02.28
[JS] 객체 - 개념 정리  (0) 2023.02.28
(JS) 배열의 반복 & 배열 메서드  (0) 2023.02.27
(JS) 배열의 기초  (0) 2023.02.27
[JS] 함수  (0) 2023.02.21
⬆︎