0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Node.jsでのObjectとArrayの使い方

0
Last updated at Posted at 2024-04-02

1. Arrayから空の要素を除く

const array = ["foo", "boo", "", "bar"];
const newArray = array.filter(Boolean); //["foo", "boo", "bar"]

const paragraph = `これは一行目です
これは二行目です

これは三行目です
これは四行目です
`;

const sentences = paragraph.split("\n").filter(Boolean);
// ["これは一行目です", "これは二行目です", "これは三行目です", "これは四行目です"]

このコード行は、JavaScriptにおいて配列から「falsy」(偽と評価される) 値を取り除く簡潔な方法を示しています。ここで使用されている .filter() メソッドは、配列の各要素に対してテスト関数を実行し、その関数が true を返した要素のみからなる新しい配列を生成します。

2. ObjectのキーをArrayにする

const users = {
 taro: {
   gender: "",
   hobby: "水泳",
 },
 jiro: {
   gender: "",
   hobby: "読書",
 },
 hanako: {
   gender: "",
   hobby: "カラオケ",
 },
};

Object.keys(users);
// output: ["taro", "jiro", "hanako"]

3. Objectの配列から特定のキーを抽出する

example.js
const items = [
 { id: 1, name: "アイテム1" },
 { id: 2, name: "アイテム2" },
 { id: 3, name: "アイテム3" },
];

items.map((item) => item.name);
// output: ["アイテム1", "アイテム2", "アイテム3"]

📌 ポイント

  • map() メソッドは、配列の各要素に対して与えられた関数を実行し、その結果からなる新しい配列を生成します。
  • (item) => item.name は各オブジェクトの name プロパティの値を返します。

4. Objectは空か判定する

example.ts
const obj = {};

console.log(if(obj));
// true

if (Object.keys(obj).length === 0) {
  console.log("");
} else {
  console.log("中身あり");
}

📌 ポイント

  • if(空のobject)はtrueが返却されるので判定できません
  • キーの数で空かどうかを判断する

5. shift()pop()

example.ts
const numbers = [1, 2, 3, 4, 5];
const firstElement = numbers.shift();
const lastElement = numbers.pop();

console.log(firstElement);  // 出力: 1
console.log(numbers);       // 出力: [2, 3, 4, 5]

console.log(lastElement);  // 出力: 5
console.log(numbers);       // 出力: [2, 3, 4]

📌 ポイント

  • shift() メソッドは、配列の先頭から要素を削除し、その要素を返します
  • pop() メソッドは、配列の末尾から要素を削除し、その要素を返します
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?