const hogeList = [
{
name: "malp",
addres: "top",
number: "333",
},
{
name: "yasuo",
addres: "mid",
number: "222",
},
{
name: "taro",
addres: "adc",
number: "111",
},
]
const hogeSort = "num"
hogeList.sort((a, b) => a[hogeSort] - b[hogeSort])
console.log(hogeList)
/** Object の配列を受け取り CSV形式の文字列に変換する Func */
const convertToCSV = (objArray) => {
const array = typeof objArray !== "object" ? JSON.parse(objArray) : objArray;
/** 1. Objectの Key を headerとして取り出す */
let str =
`${Object.keys(array[0])
.map((value) => `"${value}"`)
.join(",")}` + "\r\n";
// 2. 各オブジェクトの値をCSVの行として追加する
return array.reduce((str, next) => {
str +=
`${Object.values(next)
.map((value) => `"${value}"`)
.join(",")}` + "\r\n";
return str;
}, str);
};
/** Download・処理 */
const downloadCSV = (data, name) => {
/** Blob Object を作成する Type. CSV */
const blob = new Blob([data], { type: "text/csv" });
console.log("blob", blob);
const url = window.URL.createObjectURL(blob);
console.log("url", url);
const a = document.createElement("a");
a.setAttribute("href", url);
a.setAttribute("download", `${name}.csv`);
a.click();
a.remove();
};
/** CSVデータを作成 */
const csvData = convertToCSV(hogeList);
console.log(csvData);
// CSV・Download
downloadCSV(csvData, "hogeCsvData");
More than 1 year has passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme