javascript reduce㧠ãªãã¸ã§ã¯ãã®é åããå ã®ãªãã¸ã§ã¯ãã®idããã¼nameãå¤ã«ãããªãã¸ã§ã¯ãã«è©°ãç´ã
æç« ã«ããã¨ããããããã以ä¸ã®ãªãã¸ã§ã¯ãã®é åã
var in = [ { id : 11 , name : "ã¿ãã" , }, { id : 21 , name : "ãã¡ã" , }, { id : 45 , name : "ããã" , } ]
以ä¸ã®ããã«å¤æããã
var out = { 11 : "ã¿ãã", 21 : "ãã¡ã", 45 : "ã°ãªãª", }
主ã«ã¯ãããã°ã©ã å é¨ã§ä½¿ã£ã¦ãããªãã¸ã§ã¯ããããã»ã¬ã¯ãããã¯ã¹ãä½ãã¨ãã«ä½¿ããã¼ããªã¥ã¼ã®ãªãã¸ã§ã¯ããä½ãã¨ãã«ä½¿ã
var out = in.reduce((x,y)=>{x[y.id]=y.name;return x},{})); console.log(out)
returnãçç¥ãããã¼ã¸ã§ã³
var out = in.reduce((x,y)=>(x[y.id]=y.name) && x,{})); console.log(out)
⻠注æï¼ï¼ x[y.id]=y.name ã®é¨åã()ã§æ¬ã£ã¦(x[y.id]=y.name)
ã¨ãããã¨ãããããªãã¨y.name && xã®æ¹ãå
ã«å¦çãããã
x[y.id]=y.nameã®é¨åããé¢æ°ã ã£ããã¡ã½ããã ã£ããããã¨ãã«ã¯()ã¯å¿
è¦ãªãã
代å
¥æ(=)ã®ã¨ãã ã注æãå¿
è¦ãä¾ãã°x.concat(y.name)ã§ããã°å¤§ä¸å¤«