1
0

配列の要素を持つ配列オブジェクトを要素のみの配列オブジェクトに変換する

Last updated at Posted at 2024-03-19
  • data1.jsonをdata2.jsonにしたい
data1.json
[
  { "name": "a", 
    "id": 1,
    "status": 
      [
        { "type": "b1", "code": "b2" },
        { "type": "c1", "code": "c2" }
      ]
  },
  { "name": "d",
    "id": 4,
    "status":
    [
      { "type": "e1", "code": "e2" },
      { "type": "f1", "code": "f2" }
    ]
  }
]
data2.json
[
  { "name": "a",
    "id": 1,
    "type": "b1",
    "code": "b2"
  },
  { "name": "a",
    "id": 1,
    "type": "c1",
    "code": "c2"
  },
  { "name": "d",
    "id": 4,
    "type": "e1",
    "code": "e2"
  },
  { "name": "d",
    "id": 4,
    "type": "f1",
    "code": "f2"
  }
]
  • forEach関数を2重で回して、用意した空の配列に入れる
const data = "data1.json"
const formatData = computed(() => {
  const returnData: any[] = []
  data.value.results.forEach(d => {
    d.status?.forEach(dd => {
     returnData.push({
       name: d.name,
       id: d.id,
       type: dd.type,
       code: dd.type,
     })
    })
  })
  return returnData
})

上記処理でreturnDataがdata2.jsonになります。
気づいてしまえば簡単だけどちょっと悩んだので記事にしました。

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0