LoginSignup
6
6

More than 3 years have passed since last update.

JSONから、もっともプロパティの多い要素を取得する

Last updated at Posted at 2014-07-17

やりたい事の説明が難しい。


var list = [
    {id:1, name:"test", address:"tokyo"},
    {id:2, name:"hoge"},
    {id:3, name:"hello", address:"kyoto", tel:"090-1234"},
    {id:4, name:"world", address:"saitama", tel:"090-5678", fax:"03-0000"},
    {id:5, name:"shimizu", address:"gunma"},    
];

上記の様な配列から、もっともプロパティの多い要素(この場合なら、id:4のデータ)を取り出す。
あまり必要となる場面は無いかも知れないが、次の一行で取得できる。

list.reduce(function(a, b){ return Object.keys(a).length > Object.keys(b).length ? a : b });

->{id: 4, name: "world", address: "saitama", tel: "090-5678", fax: "03-0000"}

Object.keysに渡せばキーの一覧が取得できる。

Object.keys(
    list.reduce(function(a, b){ 
        return Object.keys(a).length > Object.keys(b).length ? a : b;
    })
)
->["id", "name", "address", "tel", "fax"]
6
6
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
6
6