5
4

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

Javascriptで、階層的な連想配列を作りたい。

Last updated at Posted at 2018-01-23

画像のsrcとaltを複数入れる配列を作りたくなった。

求めているもの

tes.json
[
 { 
   src : 'hogee.jpg',
   alt : 'hodehode'
 },
 { 
   src : 'hogegege.jpg',
   alt : 'hodehode2'
 }
]

これを配列のように作る。

作り方

tempみたいな変数用意して、そこに作って、いれる。

var data = {};
var temp = {};
temp.src = "hoge.jpg";
temp.alt = "hogehoge";
data[data.length] = temp;

これの繰り返し。

配列としてforeachにぶち込みたい

最終的にこれをやるから、この形式で格納したいのだと思う。

js.js
Object.keys(data).forEach(function(key) {
  if(data[key].src){
     console.log(data[key].src);
     console.log(data[key].alt);
  }
});
5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?