새오의 개발 기록

Javascript: Object.keys() 배열 내 속성 값이 존재하는 것만 추출하기 본문

프로젝트

Javascript: Object.keys() 배열 내 속성 값이 존재하는 것만 추출하기

새오: 2022. 9. 6. 13:41

조건

- 콘텐츠 추가 form에서 사용자에게 입력을 받아 콘텐츠 추가 post 요청을 보낸다. 

- contentsData 객체에는 link, favorite, comment, deadline, categoryName, title 6개의 속성이 있다.

- 이 속성들 중 link만 사용자에게 필수 값으로 입력 받으며 favorite은 default로 false 값을 갖는다. 나머지 값들은 선택 입력이다.

- 선택 입력 중 사용자가 입력하지 않은 값은 요청을 보낼 때 포함하지 않는다.

 

 

 

구현 방법

- contentData 객체 내 값이 "" 이거나 undefined 인 속성을 삭제한다.

- Object.keys() 객체의 속성 이름들을 순회하며 받은 배열에 forEach를 걸어 속성 값이 "" 이거나 undefined인 속성을 삭제하는 함수를 실행하면 값이 있는 속성만 들어있는 객체를 구할 수 있다.

 

Object.keys()

- 주어진 객체의 속성 이름들을 일반적인 반복문과 동일한 순서로 순회되는 열거할 수 있는 배열로 반환함

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

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

 

 

Array.prototype.forEach()

- 주어진 함수를 배열 요소 각각에 대해 실행함

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

 

 

 

 

 

전체 코드

// 콘텐츠 추가 요청
	async createContent() {
        const contentsData = {
          link: this.link,
          favorite: this.favorite,
          comment: this.comment,
          deadline: this.deadline,
          categoryName: this.categoryName,
          title: this.title,
        };
        Object.keys(contentsData).forEach(
          (key) =>
            (contentsData[key] == "" || contentsData[key] == undefined) &&
            delete contentsData[key]
        );
        console.log(contentsData);
          try {
            const response = await addContents(contentsData);
            console.log(response);
            this.$emit("close-modal");
          } catch (error) {
            console.log(error);
            this.alertModalContent = error.response.message;
            this.isAlertModalActive = true;
          }
        }

 

 

 

 

삽질 이유

- js 내장 메소드를 사용할 생각을 못하고 입력 경우의 수 생각해서 다 if문으로 처리하려고 했다.

- 위 방법이 비효율적인 것 뿐만 아니라 내가 생각한 경우가 조건문에 걸리지도 않아서 헤맸다.