Java Scripts

Javascripts destructuring

HobbyCoding 2021. 12. 28. 09:19
728x90

 

정의

Arrays나 object 의 property 에서 필요한 array element 나 field data 만 distinct 한 변수에 담아오는 표현법임

 

 

용례

ex1 )  배열에서  descructure 하는 방법

const x = [1, 2, 3, 4, 5];
const [y, z] = x;  // 1 과 2가 각각 y, z 에 assign 됨 
console.log(y);    // 1 
console.log(z);    // 2

 

 

ex2 )  object 에서 descructure 하는 방법

const obj = { a: 1, b: 2 };
const { a, b } = obj;
// is equivalent to:
// const a = obj.a;
// const b = obj.b;

 

 

ex 3) Obj 에서 필요한 field 만 변수 담아옴

const updateJob = async (req, res) => {
  const {
    body: { company, position },  
    // 변수 company, position 로 req로 부터 data 가 들어간다.
    // req 구조는 req.body.company,  req.body.position , 로 되어 있을 것임
    user: { userId },
    params: { id: jobId }, // id 는 key고 jobid 는 변수임
  } = req

  if (company === '' || position === '') {
    throw new BadRequestError('Company or Position fields cannot be empty')
  }
  const job = await Job.findByIdAndUpdate(
    { _id: jobId, createdBy: userId },
    req.body,
    { new: true, runValidators: true }
  )
  if (!job) {
    throw new NotFoundError(`No job with id ${jobId}`)
  }
  res.status(StatusCodes.OK).json({ job })
}

 

 

ex 4) Obj 에서 필요한 field 만 변수 담아옴 sub object 처리하는 방법도 있음

const deleteJob = async (req, res) => {
  const {
    user: { userId },
    params: { id: jobId },  // param 안에 sub objec가 있고 이안의 id field 를 가지고 온다
  } = req

  const job = await Job.findByIdAndRemove({
    _id: jobId,
    createdBy: userId,
  })
  if (!job) {
    throw new NotFoundError(`No job with id ${jobId}`)
  }
  res.status(StatusCodes.OK).send()
}