ホームページ ウェブフロントエンド jsチュートリアル ネストされたオブジェクト内のパスを取得して検証する - util 関数 #2

ネストされたオブジェクト内のパスを取得して検証する - util 関数 #2

Nov 19, 2024 pm 09:19 PM

Get and verify paths in a nested object - util functions #2

昨日、JS でオブジェクトを繰り返しループするユーティリティ関数を共有しました。その機能の 1 つは、ネストされたオブジェクトへのパスを含む配列を取得できることです。現在ループ中です。ただし、ネストされたオブジェクトを操作するときは、いつでも特定のパスからデータを取得または検証することが必要になる場合があります。これが、今日のユーティリティ関数の機能です。

  • getDataFromObj(obj, path): オブジェクト内の指定されたパスからデータを取得します
  • isValidObjPath(obj, path): 指定されたパスがオブジェクトに存在するかどうかを確認します

getDataFromObj(obj, パス)

このコードを自由にコピーして貼り付けてください

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

/**

 * Retrieves data from an object on a given path

 * @param {Object} obj the object to get the data from

 * @param {string[]} path an array of strings containing the keys of the object to look at

 * @returns {*} the retrieved data or a Reference Error if not found

 */

 

function getDataFromObj(obj, path){

  // Validate arguments

  if(getType(obj) != "object"){

    throw TypeError("The `obj` argument is not an object");

  }

  if(getType(path) != "array"){

    throw TypeError("The `path` argument is not an array");

  }

 

  // Get the data or a ReferenceError if not found

  const data = (()=>{

    let currentData = obj;

 

    for(let i = 0; i < path.length; i +=1 ){

      if(Object.keys(currentData).includes(path[i])){

        currentData = currentData[path[i]];

        continue;

      } else{

        currentData = ReferenceError("The object path is not defined");

        break;

      }

    }

    return currentData;

  })();

 

  return data;

}

 

/**

 * A method to detect data types more accurately

 * Credits: Chris Ferdinandi, https://gomakethings.com/

 * @param {*} data the data to be verified

 * @returns {String} the data type

 */

function getType(data){

  return Object.prototype.toString.call(data).toLowerCase().slice(8, -1)

}

 

/**

 * License: MIT, https://opensource.org/license/mit

 * Copyright (c) 2024 Rodrigo Isaias Calix

 */

ログイン後にコピー

使用法:

2 つの引数を渡す必要があります:
obj: データを取得するオブジェクト
path: 従うシーケンスを示す配列

パスが存在する場合は値が返されます (値が未定義であっても)。パスが存在しない場合は ReferenceError オブジェクトが返されます。エラーはスローされず、エラー オブジェクトのみが返されます。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

const products = {

  computers: {

    laptop: 20,

    desktop: 15,

    mini: 8

  },

  cameras: 20,

  externalDevices: {

    keyboard: {

      usb: 45,

      bluetooth: 25,

      other: undefined

    }

  }

}

 

// This would log 25

console.log(getDataFromObj(products, ["externalDevices", "keyboard", "bluetooth"]))

 

// this would return a ReferenceError object (not a throw, just the error object)

console.log(getDataFromObj(products, ["externalDevices", "mouse"]))

 

// this would return `undefined`

console.log(getDataFromObj(products, ["externalDevices", "keyboard", "other"]))

ログイン後にコピー

isValidObjPath(obj, パス)

ユーティリティコード:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

/**

 * verify if an object has an specific path

 * @param {Object} obj the object to be verified

 * @param {string[]} path an array of strings containing the keys of the object to look at

 * @returns {Boolean} `true` if found, otherwise `false`

 */

function isValidObjPath(obj, path){

  // Validate arguments

  if(getType(obj) != "object"){

    throw TypeError("The `obj` argument is not an object");

  }

  if(getType(path) != "array"){

      throw TypeError("The `path` argument is not an array");

  }

 

  // shallow copy of the object to be verified

  let currentData = obj;

 

  // Verify the path

  for(let i = 0; i < path.length; i +=1 ){

    if(Object.keys(currentData).includes(path[i])){

      currentData = currentData[path[i]];

      continue;

    } else{

      return false;

    }

  }

 

  return true;

}

 

/**

 * A method to detect data types more accurately

 * Credits: Chris Ferdinandi, https://gomakethings.com/

 * @param {*} data the data to be verified

 * @returns {String} the data type

 */

function getType(data){

  return Object.prototype.toString.call(data).toLowerCase().slice(8, -1)

}

 

/**

 * License: MIT, https://opensource.org/license/mit

 * Copyright (c) 2024 Rodrigo Isaias Calix

 */

ログイン後にコピー

使用法:

2 つの引数を渡す必要があります:
obj: パスが存在するかどうかを確認するオブジェクト
path: 従うシーケンスを示す配列

検索しているパスが存在する場合は true を返し、存在しない場合は false を返します

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

const products = {

  computers: {

    laptop: 20,

    desktop: 15,

    mini: 8

  },

  cameras: 20,

  externalDevices: {

    keyboard: {

      usb: 45,

      bluetooth: 25,

      other: undefined

    }

  }

}

 

// This would log true

console.log(isValidObjPath(products, ["externalDevices", "keyboard", "bluetooth"]))

 

// this would log false

console.log(isValidObjPath(products, ["externalDevices", "mouse"]))

 

// this would log true

console.log(isValidObjPath(products, ["externalDevices", "keyboard", "other"]))

ログイン後にコピー

なぜスラッシュやドットを含む文字列ではなく配列をパスとして使用するのでしょうか? (例: 「コンピューター.ラップトップ」)

オブジェクトのプロパティ名は、ドットを含む広範囲の文字セットを含む文字列にすることもできるため、たとえば、「computers.laptop」: {[...]} は有効なオブジェクト、配列になります。柔軟性と正確性がさらに高まります。


これが役立つと思われた場合は、DEV でこのようなコンテンツをさらに共有します!

X: https://x.com/schemetastic

でも私を見つけることができます。

後で使うために忘れずに保存してください ?

以上がネストされたオブジェクト内のパスを取得して検証する - util 関数 #2の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットな記事タグ

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

JavaScriptの文字列文字を交換します JavaScriptの文字列文字を交換します Mar 11, 2025 am 12:07 AM

JavaScriptの文字列文字を交換します

カスタムGoogle検索APIセットアップチュートリアル カスタムGoogle検索APIセットアップチュートリアル Mar 04, 2025 am 01:06 AM

カスタムGoogle検索APIセットアップチュートリアル

例JSONファイルの例 例JSONファイルの例 Mar 03, 2025 am 12:35 AM

例JSONファイルの例

8見事なjQueryページレイアウトプラグイン 8見事なjQueryページレイアウトプラグイン Mar 06, 2025 am 12:48 AM

8見事なjQueryページレイアウトプラグイン

10 jQuery構文蛍光物 10 jQuery構文蛍光物 Mar 02, 2025 am 12:32 AM

10 jQuery構文蛍光物

独自のAjax Webアプリケーションを構築します 独自のAjax Webアプリケーションを構築します Mar 09, 2025 am 12:11 AM

独自のAjax Webアプリケーションを構築します

' this' JavaScriptで? ' this' JavaScriptで? Mar 04, 2025 am 01:15 AM

' this' JavaScriptで?

10 JavaScript&JQuery MVCチュートリアル 10 JavaScript&JQuery MVCチュートリアル Mar 02, 2025 am 01:16 AM

10 JavaScript&JQuery MVCチュートリアル

See all articles