Function stringify
- stringify(data, options?): string
Parameters
- data: readonly DataItem[]
The source data to stringify. It's an array of items which are plain objects or arrays.
Optionaloptions: StringifyOptionsOptions for the stringification.
Returns string
A CSV string.
Example: Give an array of objects and specify columns
import { stringify } from "@std/csv/stringify";
import { assertEquals } from "@std/assert/equals";
const data = [
{ name: "Rick", age: 70 },
{ name: "Morty", age: 14 },
];
const columns = ["name", "age"];
assertEquals(stringify(data, { columns }), `name,age\r\nRick,70\r\nMorty,14\r\n`);Example: Give an array of objects and specify columns with `headers: false`
import { stringify } from "@std/csv/stringify";
import { assertEquals } from "@std/assert/equals";
const data = [
{ name: "Rick", age: 70 },
{ name: "Morty", age: 14 },
];
const columns = ["name", "age"];
assertEquals(
stringify(data, { columns, headers: false }),
`Rick,70\r\nMorty,14\r\n`,
);Example: Give an array of objects and specify columns with renaming
import { stringify } from "@std/csv/stringify";
import { assertEquals } from "@std/assert/equals";
const data = [
{ name: "Rick", age: 70 },
{ name: "Morty", age: 14 },
];
const columns = [
{ prop: "name", header: "user name" },
"age",
];
assertEquals(
stringify(data, { columns }),
`user name,age\r\nRick,70\r\nMorty,14\r\n`,
);Example: Give an array of objects with nested property and specify columns
import {
Column,
stringify,
} from "@std/csv/stringify";
import { assertEquals } from "@std/assert/equals";
const data = [
{
age: 70,
name: {
first: "Rick",
last: "Sanchez",
},
},
{
age: 14,
name: {
first: "Morty",
last: "Smith",
},
},
];
const columns: Column[] = [
["name", "first"],
"age",
];
assertEquals(
stringify(data, { columns }),
`first,age\r\nRick,70\r\nMorty,14\r\n`,
);Example: Give an array of objects with nested property and specify columns
with renaming
import {
Column,
stringify,
} from "@std/csv/stringify";
import { assertEquals } from "@std/assert/equals";
const data = [
{
age: 70,
name: {
first: "Rick",
last: "Sanchez",
},
},
{
age: 14,
name: {
first: "Morty",
last: "Smith",
},
},
];
const columns: Column[] = [
{ prop: ["name", "first"], header: "first name" },
"age",
];
assertEquals(
stringify(data, { columns }),
`first name,age\r\nRick,70\r\nMorty,14\r\n`,
);Example: Give an array of string arrays and specify columns with renaming
import { stringify } from "@std/csv/stringify";
import { assertEquals } from "@std/assert/equals";
const data = [
["Rick", 70],
["Morty", 14],
];
const columns = [
{ prop: 0, header: "name" },
{ prop: 1, header: "age" },
];
assertEquals(
stringify(data, { columns }),
`name,age\r\nRick,70\r\nMorty,14\r\n`,
);- data: readonly DataItem[]
Converts an array of objects into a CSV string.