rest + spread(응용)1

객체의 데이터들(오리지날 데이터)을 복사해와서 제 사용하기

const slime = {
    name: '슬라임',
    attribute: 'cute',
    color: 'purple'
};

const { ...rest } = slime; // 복사해오는 코드 
const ex = { so: {...rest} } // 복사해온 코드를 리마인드 하기 

ex.so.name = 'triplexlab' //복사해온 데이터중에 name값을 변경해보자 
console.log(ex.so)    //복사해온 코드를 출력해보자! 
console.log(slime)    //원본 데이터를 출력해보자!
// 결과)
{ name: 'triplexlab', attribute: 'cute', color: 'purple' }
{ name: '슬라임', attribute: 'cute', color: 'purple' }

객체의 데이터들을 배열로 받아오기

// 이런 객체가 있다고 가정해보자
const purpleCuteSlime = {
    name: '슬라임',
    attribute: 'cute',
    color: 'purple'
};

위에 있는 데이터를 배열로 감싸서 받아오자

const { ...restd } = purpleCuteSlime;

function arry(...params) {
   console.log(params)
}

arry(restd);
// 결과)
[ { name: '슬라임', attribute: 'cute', color: 'purple' } ]

객체의 데이터들(오리지날 데이터)을 복사해와서 특정 부분만 수정하기

var person = {
  name: "jane",
  age: 16,
  family: [ //family 부분을 so로 키명을 변경하고 싶다면.
    {
      name: "jack",
      age: 15
    },
    {
      name: "tom",
      age: 40
    },
  ]
};
const { ...res } = person; //객체 데이터 전체를 복사해온다. 
const newPerson = { so : [...res.family] }; //{ 변경하고픈 명: [ 복사해온 데이터.원하는 위치(depth) ]}
console.log(newPerson)
// 결과)
{ so: [ { name: 'jack', age: 15 }, { name: 'tom', age: 40 } ] }
var person = {
  depth_1: {
      depth_2: {
        depth_3: {
          depth_4_1: 'faded',
          depth_4_2: true // 요놈을 바꾸고 싶다!
        },
        depth_3_1: 'lost'
      },
      depth_2_1: {
        depth_3_2: true,
        depth_3_3: false
      }
  }
};
const { ...res } = person;
const newPerson = { ...res.depth_1.depth_2.depth_3 };

newPerson.depth_4_2 = false
console.log(newPerson)
// 결과)
{ depth_4_1: 'faded', depth_4_2: false }

배열의 원소들을 모두 더한 값을 구하기

function sum(...params) { //rest하게 받는것
  return params.reduce((acc, current) => acc + current, 0);
}

const number = [1, 2, 3, 4, 5, 6, 7];
console.log(sum(...number)); //spread하게 넘겨주는
// 결과)
28

Last updated