카테고리 없음

[JS] 객체내 Values null값 제거 feat:구조분해할당, Object.entries

0hyeon의 2023. 4. 5. 18:05
반응형

 

1.문제

프로젝트를 진행하며 객체내에 원하지않는 null값을 빼주고 싶어서 좋은 코드를 조합하여, 공유하고자합니다. ES6문법 중에 구조분해할당과 Object.entries를 사용한 코드입니다.

데이터는 다음과 같습니다.

[
    {
        "clientId": 32,
        "clientName": "김영현",
        "contact": "01041096590",
        "clientEmail": "djdjdjk2006@naver.com",
        "groupId": 6,
        "groupName": "33",
        "talkContentId": 36,
        "talkTemplateId": 2,
        "organizationName": null,
        "customerName": "김영현",
        "orderNumber": null,
        "region": null,
        "regionDetail": null,
        "deliveryDate": null,
        "paymentPrice": null,
        "deliveryCompany": "32",
        "deliveryTime": "32",
        "deliveryNumber": "01041096590",
        "useLink": null,
        "trackingUrl": null,
        "createdAt": "2023-04-04T18:22:03.000Z"
    },
    {
        "clientId": 31,
        "clientName": "김영현",
        "contact": "01041096590",
        "clientEmail": "djdjdjk2006@naver.com",
        "groupId": 6,
        "groupName": "33",
        "talkContentId": 37,
        "talkTemplateId": 2,
        "organizationName": null,
        "customerName": "김영현",
        "orderNumber": null,
        "region": null,
        "regionDetail": null,
        "deliveryDate": null,
        "paymentPrice": null,
        "deliveryCompany": "31",
        "deliveryTime": "31",
        "deliveryNumber": "01041096590",
        "useLink": null,
        "trackingUrl": null,
        "createdAt": "2023-04-04T18:22:03.000Z"
    }
]

여기서 values의 null값을 빼려면 다음과 같습니다. 

 

const result = Data.map((item: any) => {
    for (const [key, value] of Object.entries(item)) {
      if (value === null) {
        item[key] = '';
      }
    }
    return item;
 });

반복문 안에서 key와 value로 구조 분해할당을 진행한뒤  (1) object.entreis() 메서드를 사용하면 됩니다.

 

(1) Object.entries(obj)  [키, 값] 쌍을 담은 배열을 반환합니다.

 

let user = {
  name: "John",
  age: 30
};

//output :  [ ["name","John"], ["age",30] ]

반응형