javascript lodashを使ってパスから配列を作成する
- 作成日 2022.03.15
- javascript lodash
- javascript, lodash

javascriptで、lodashを使ってパスから配列を作成するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- lodash 4.17.21
- ブラウザ chrome 91.0.4472.77
lodash使用
こちらのサイトから最新版を確認して、CDN版を使用してます。
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

パスから配列を作成
パスから配列を作成するには、「_.toPath」を使用します。
'use strict';
console.log(
_.toPath('a.b.c')
// ["a", "b", "c"]
)
console.log(
_.toPath('a[0].b[1].c[2]')
// ["a", "0", "b", "1", "c", "2"]
)
実行結果を確認すると、配列が作成されていることが確認できます。

サンプルコード
以下は、
「実行」ボタンをクリックして、パスから配列を生成した結果を表示するサンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>
<script>
const hoge = () => {
const str = 'aaa.bbb.ccc'
foo.innerHTML = str
bar.innerHTML = _.toPath(str)
}
window.onload = () => {
btn.onclick = () => { hoge() }
}
</script>
<body>
<div class="container mx-auto my-56 w-1/3 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 class="font-semibold text-green-500 text-lg mr-auto">パス</h1>
<h1 id="foo" class="font-semibold text-green-500 text-lg mr-auto"></h1>
<h1 class="font-semibold text-gray-500 text-lg mr-auto">実行結果</h1>
<h1 id="bar" class="font-semibold text-gray-500 text-lg mr-auto"></h1>
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-purple-300 text-purple-700 font-semibold hover:text-white py-2 px-4 border border-purple-300 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、結果が表示されていることが確認できます。

-
前の記事
Linux プロセス名からプロセスIDを取得する 2022.03.14
-
次の記事
sqlite 指定した位置から文字列を取得する 2022.03.15
コメントを書く