ore88ore memo

プログラミング関連のTipsをメインに書いていきます。どなたかのお役に立てれば幸いです。

Javascriptで配列を便利に操作

配列の中がオブジェクトで構成されているような配列を操作したい時のTipsです。

const array = [
    {id: "id1", name: "hoge"},
    {id: "id2", name: "foo"},
];

nameだけ取得する

const array = [
    {id: "id1", name: "hoge"},
    {id: "id2", name: "foo"},
];
const names = array.map((currentValue, index, array) => {
    // currentValueは、配列内のアイテム
    return currentValue.name;
});
console.log(names);
// ["hoge", "foo"]

nameだけの配列から重複を削除する

const array = ["hoge", "foo", "foo2", "hoge"];
const newArray = Array.from(new Set(array));

console.log(array);
// ["hoge", "foo", "foo2", "hoge"]

console.log(newArray);
// ["hoge", "foo", "foo2"]

idがid1のアイテムだけ取得する

const array = [
    {id: "id1", name: "hoge"},
    {id: "id2", name: "foo"},
];
const id1 = array.find((element, index, array) => {
    // elementは、配列内のアイテム
    return element.id === "id1";
});
console.log(id1);
// {id: "id1", name: "hoge"}

idがid1のアイテムだけ配列で取得する

1つの特定のオブジェクトを取得する場合は、上記のfindのほうが良いかと思います。

const array = [
    {id: "id1", name: "hoge"},
    {id: "id2", name: "foo"},
];
const id1 = array.filter((currentValue, index, array) => {
    // currentValueは、配列内のアイテム
    return currentValue.id === "id1";
});
console.log(id1);
// [{id: "id1", name: "hoge"}]

idがid1のアイテムが存在するか?

const array = [
    {id: "id1", name: "hoge"},
    {id: "id2", name: "foo"},
];
const isExists = array.some((element, index, array) => {
    // elementは、配列内のアイテム
    return element.id === "id1";
});
console.log(isExists);
// true