0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【JavaScript】データの一部をkeyにリスト型をオブジェクト型に成型する

Last updated at Posted at 2023-07-03

初心者の備忘。

やりたいこと

配列をオブジェクトのオブジェクトにする。

//START
sampleList=[
         {no:1, name:hoge, value:"ほげ"}
        ,{no:2, name:fuge, value:"ふげ"}
        ,{no:3, name:fuga, value:"ふが"}
       ]

//GOAL
sampleObject = {
         1:{no:1, name:hoge, value:"ほげ"}
        ,2:{no:2, name:fuge, value:"ふげ"}
        ,3:{no:3, name:fuga, value:"ふが"}
        }

サンプルコード

sanple.js
let sampleObject = {}; //空のオブジェクトを宣言
sampleList.forEach(function(list){
   sampleObject[list.no]=list; 
});

ちょっと解説

Object[key名]=value名で、Objectの中に{key:value}のオブジェクトが作られる。
forEachで回すことで、複数の配列をすべてObject型に変更可能。
配列の値を使わずにkey名を決めるなら、通常のfor文でiとかをkeyに充てればよい。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?