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

JavaScirpt オブジェクト配列のコールバック処理サンプル

Last updated at Posted at 2019-10-04

JavaScriptの配列で、コールバック関数を使って処理するサンプルです。

数値配列のサンプルは多いのですが、オブジェクトの配列を処理するサンプルが少ない気がしたので。

var list = [
    { id: "A01", name: "yama" },
    { id: "B02", name: "matu" },
    { id: "C03", name: "moto" },
    { id: "D04", name: "sato" },
];

console.log(`${list.length} Members`);
// "4 Members"

// find
let m;
m = list.find(function (x) {
    return x.id == "C03";
});
console.log(`${m.id} is ${m.name}.`);
// "C03 is moto."

// 簡略形式(上記と同じ)
m = list.find(x => x.id == "C03");
console.log(`${m.id} is ${m.name}.`);
// "C03 is moto."

// 全件処理(forEach)
list.forEach(x => console.log(`- ${x.id} : ${x.name}`));
// - A01 : yama
// - B02 : matu
// - C03 : moto
// - D04 : sato

// 加工した別配列を作る(map)
let nameList = list.map(x => x.name.toUpperCase());
console.log(nameList);
// [ 'YAMA', 'MATU', 'MOTO', 'SATO' ]

// 配列を1つにまとめる(reduce)
let title = list.reduce((a, b) => {
    return a += b.name[0].toUpperCase(); // nameの最初の一文字を取得し大文字に
}, "");
console.log(title);
// "YMMS"

// IDが一番大きい人は?
let maxIdMember = list.reduce((a, b) => {
    return a.id > b.id ? a : b;
});
console.log(maxIdMember);
// { id: 'D04', name: 'sato' }

// filter
console.log(list.filter(x => x.name[0] == "m"));
// [ { id: 'B02', name: 'matu' }, { id: 'C03', name: 'moto' } ]

// sort
list.sort((a, b) => a.name > b.name); // sort()は、配列を変更する。
console.log(list);
// [ { id: 'B02', name: 'matu' }, { id: 'C03', name: 'moto' }, { id: 'D04', name: 'sato' }, { id: 'A01', name: 'yama' } ]
2
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
2
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?