untranspose
v0.0.2
Published
Convert column-oriented arrays into row-oriented objects
Readme
untranspose
Convert column-oriented arrays into row-oriented objects.
untranspose is a small CommonJS utility for turning data shaped like this:
{
name: ["Ada", "Grace"],
language: ["Lovelace", "COBOL"]
}into data shaped like this:
[
{ name: "Ada", language: "Lovelace" },
{ name: "Grace", language: "COBOL" }
]Installation
npm install untransposeUsage
const untranspose = require("untranspose");
const rows = untranspose({
id: [1, 2, 3],
name: ["Ada", "Grace", "Katherine"],
active: [true, false, true]
});
console.log(rows);
// [
// { id: 1, name: "Ada", active: true },
// { id: 2, name: "Grace", active: false },
// { id: 3, name: "Katherine", active: true }
// ]API
untranspose(data, emptyValue)
Returns an array of row objects.
data
Type: Object
An object whose keys are field names and whose values are arrays.
untranspose({
a: ["a1", "a2"],
b: ["b1", "b2"]
});
// [
// { a: "a1", b: "b1" },
// { a: "a2", b: "b2" }
// ]The number of output rows is based on the length of the first field's array.
untranspose({
a: [1, 2, 3],
b: ["one"]
});
// [
// { a: 1, b: "one" },
// { a: 2 },
// { a: 3 }
// ]If data has no fields, the result is an empty array.
untranspose({});
// []emptyValue
Type: any
Default: undefined
Values that are strictly equal to emptyValue are omitted from each row.
By default, undefined values are omitted.
untranspose({
name: ["Ada", "Grace"],
score: [100, undefined]
});
// [
// { name: "Ada", score: 100 },
// { name: "Grace" }
// ]You can pass a custom value to omit:
untranspose({
name: ["Ada", "Grace"],
score: [100, null]
}, null);
// [
// { name: "Ada", score: 100 },
// { name: "Grace" }
// ]Falsy values are preserved unless they match emptyValue.
untranspose({
count: [0, 1],
enabled: [false, true],
label: ["", "ready"]
});
// [
// { count: 0, enabled: false, label: "" },
// { count: 1, enabled: true, label: "ready" }
// ]CommonJS
This package uses CommonJS:
const untranspose = require("untranspose");TypeScript
Type definitions are included.
import untranspose = require("untranspose");
const rows = untranspose({
id: [1, 2, 3],
name: ["Ada", "Grace", "Katherine"],
score: [100, undefined, 95]
});
// rows is Array<{
// id?: number;
// name?: string;
// score?: number;
// }>With esModuleInterop or compatible module settings, default imports can also
work in TypeScript projects:
import untranspose from "untranspose";Development
Run the test suite with:
npm testLicense
MIT
