tags : TypeScript

分割代入

英語 Destructuring assignment

オブジェクトのパラメータ構造を変えたい

あるオブジェクトの木構造を変更するには 分割代入 を使うとよい。

//
// response の型を ResultTypeに変える
//
const response = {
  type: "outline",
  results: {
    title: "タイトル",
    text: "テキスト",
    image: {
      src: "https://dev-npp-cms.rzm.io/wp-content/uploads/2021/01/outline.jpg"
    },
    caption: "caption"
  }
}
 
type ResultType = {
  type: string
  title: string,
  text: string,
  image: string,
  caption: string
}
 
const { results: {image: {src}, ...results }, ...others } = response
const result = { image: src, ...results, ...others} as ResultType
console.log(result)
 

{ image: ‘https://dev-npp-cms.rzm.io/wp-content/uploads/2021/01/outline.jpg’, title: ‘タイトル’, text: ‘テキスト’, caption: ‘caption’, type: ‘outline’ }