javascript オブジェクトを文字列に変換する
- 作成日 2022.03.05
- 更新日 2022.10.17
- javascript
- javascript

javascriptで、オブジェクトを文字列に変換するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 106.0.5249.103
文字列に変換
オブジェクトを文字列に変換するには、「Object.entries」で配列に変えて、
「map」でプロパティ値だけに「:」を付与して、最後に「join」で改行を付与します。
const obj = {
"a": "100",
"b": "200",
"c": "300"
}
const str = Object.entries(obj).map(x => x.join(":")).join("\n");
console.log(str);
実行結果

「{」をつけると、よりオブジェクトっぽく見えます。
console.log(`obj = {\n${str}\n}`);
実行結果

サンプルコード
以下は、
「実行」ボタンをクリックした際に、用意したオブジェクトを文字列に変換して表示するサンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
</head>
<script>
const obj = {
"a": "100",
"b": "200",
"c": "300"
}
window.onload = () => {
btn.onclick = () => {
foo.innerHTML = Object.entries(obj).map(x => x.join(":")).join("<br>")
}
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<h1 class="font-semibold text-pink-500 text-lg mr-auto">実行結果</h1>
<p id="foo" class="font-semibold text-lg mr-auto"></p>
<button id="btn"
class="mb-2 md:mb-0 bg-transparent hover:bg-blue-500 text-blue-700 font-semibold hover:text-white py-2 px-4 border border-blue-500 hover:border-transparent rounded">
実行
</button>
</div>
</div>
</body>
</html>
実行結果を確認すると、オブジェクトが表示されていることが確認できます。

-
前の記事
python sqliteをweb上から操作する「sqlite-web」を構築する 2022.03.04
-
次の記事
C# 配列またはリストの合計値を取得する 2022.03.05
コメントを書く