0
1

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 3 years have passed since last update.

【JavaScript】配列・オブジェクト(map, forEach)

Posted at

はじめに

プログラミングを勉強しはじめて、配列・オブジェクトなどの値をどう変化させるのか、どうとっていけばいいのかと悩むことが多くなってきたので、オブジェクトから配列へ、配列からオブジェクトへどう変化していくのかどうすればいいのかを書きました。

使うデータ(initialData)

const data = [
  { name: "taro", age: 17, gender: 0 },
  { name: "tarako", age: 18, gender: 0 },
  { name: "takeru", age: 19, gender: 1 }
];

配列の中にそれぞれのkeyを持つオブジェクトのデータ

mapを使ってみる

const mapData = data.map((data) => ({
  name: data.name,
  age: data.age,
  gender: data.gender
}));

// 出力
console.log(mapData)

// 結果
[
  { name: "taro", age: 17, gender: 0 },
  { name: "tarako", age: 18, gender: 0 },
  { name: "takeru", age: 19, gender: 1 }
]

forEachを使ってみる

const objList = {}
const arrayList = []

const foreachdata = data.forEach((data, index) => {
 const name = data.name
 objList[index] = name
 
 arrayList.push(data)
}

// 出力
console.log(objList)
console.log(arrayList)

// 結果

//objList
{
  "0": "taro",
  "1": "tarako",
  "2": "takeru"
}

//arrayList
[
  { name: "taro", age: 17, gender: 0 },
  { name: "tarako", age: 18, gender: 0 },
  { name: "takeru", age: 19, gender: 1 }
]

配列データをオブジェクトデータに

const objData = {...data}

// 出力
console.log(objData)
console.log(objData[0])
console.log(objData[0].name)

// 結果
{
  "0": { name: "taro", age: 17, gender: 0 },
  "1": { name: "tarako", age: 18, gender: 0 },
  "2": { name: "takeru", age: 19, gender: 1 }
}

{ 
  name: "taro", 
  age: 17,  
  gender: 0 
}

"taro"

オブジェクトに変換してkeyを追加してみた

// key=id データ
const idData= [
  "3k3BY9fFF2orKZ2KK5iD",
  "PT5aOkhANVxVfFMRkTFJ",
  "cAdMjNY0vxPLgrKH6oNN",
]

// 処理
const newData = {}

idData.forEach((id) => {
  data.forEach((d) => {
     newData[i] = d
  }
}

// 出力
console.log(newData)

// 結果
{
  "3k3BY9fFF2orKZ2KK5iD": { 
     "name": "taro",
     "age": 17, 
     "gender": 0 
  },
  "PT5aOkhANVxVfFMRkTFJ": {
      "name": "tarako", 
      "age": 18, 
      "gender": 0 
  },
  "cAdMjNY0vxPLgrKH6oNN": { 
      "name": "takeru", 
      "age": 19, 
      "gender": 1 
  }
}

終わりに

まだまだ勉強中なもので、もっとこうしたらいいなどのアドバイス等があれば宜しくお願いします!

0
1
0

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?