LoginSignup
22
15

More than 5 years have passed since last update.

連想配列の中から、特定要素の値を取り出してフラットなリストを作る

Posted at

例えば、下記のような連想配列から画像ファイルのリストを作りたいときに使う。

var data = [
  {
    name:"shimizu",
    address:"takasaki",
    img1:"shimzu.jpg",
    img2:"takasaki.jpg"
  },
  {
    name:"hoge",
    address:"maebashi",
    img1:"hoge.jpg",
    img2:"maebashi.jpg"
  },
  {
    name:"test",
    address:"kiryu",
    img1:"test.jpg",
    img2:"kiryu.jpg"
  },
  {
    name:"bob",
    address:"fujioka",
    img1:"bob.jpg",
    img2:"fujioka.jpg"
  },
  {
    name:"tanaka",
    address:"ota",
    img1:"tanaka.jpg",
    img2:"ota.jpg"
  },
]

取り出してリストにする。

var imgFileList = data.map(function(row){
    return [ row["img1"], row["img2"] ]
  }).reduce(function(a,b){
    return a.concat(b);
  });

console.log(imgFileList);
> ["shimzu.jpg", "takasaki.jpg", "hoge.jpg", "maebashi.jpg", "test.jpg", "kiryu.jpg", "bob.jpg", "fujioka.jpg", "tanaka.jpg", "ota.jpg"]

22
15
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
22
15