[Javascript] Object.keys()

박세화·2023년 6월 5일

Javascript

목록 보기
3/12
const CategoriesPreview = () => {
  const { categoriesMap } = useContext(CategoriesContext);

  return (
    <div className="categories-preview-container">
      {Object.keys(categoriesMap).map((title) => {
        const products = categoriesMap[title];
        return (
          <CategoryPreview key={title} title={title} products={products} />
        );
      })}
    </div>
  );
};

Object.keys(categoriesMap) : ['hats', 'jackets', 'women'....]

Object.keys()

The Object.keys() static method returns an array of a given object's own enumerable string-keyed property names.

괄호 안에 들어간 객체의 key값들만 뽑아서 string 타입 array로 리턴한다

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

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

📌 이 때 key값이 숫자로 되어있더라도 string으로 바뀌어서 리턴된다는 것 주의!

const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.keys(obj)); 

// output ['0', '1', '2']

0개의 댓글