Skip to content

Commit

Permalink
Fix object format and add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
phieronymus committed Dec 17, 2020
1 parent 028a0df commit f58865e
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/utils/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,16 @@ export const transformKeys = (
return transformArray(obj, transformer);
}

const ignoredKeySet = new Set(ignoreKeys);
const ignoredKeySet = new Set(ignoreKeys || []);
return Object.keys(obj || {}).reduce((acc: Record<string, any>, key: string) => {
const formattedKey = ignoredKeySet.has(key) ? key : transformer(key);
const value = isObject(obj[key]) ? transformKeys(obj[key], transformer) : obj[key];
const value = obj[key];

acc[formattedKey] = value;
if (ignoredKeySet.has(key)) {
return { ...acc, [key]: value };
}

const formattedValue = isObject(obj[key]) ? transformKeys(obj[key], transformer) : obj[key];
acc[transformer(key)] = formattedValue;
return acc;
}, {});
};
Expand Down
51 changes: 51 additions & 0 deletions test/specs/object.specs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { expect } from "chai";
import { snakeCase } from "change-case";

import { transformKeys } from "../../src/utils/object";

describe("Object Helpers", () => {
it("should format the object keys recursively", () => {
const data = {
key1: "Value 1",
key2: { key21: "Value 2" },
myKey1: {
mySubKey11: "Value 3-1",
mySubKey12: "Value 3-2",
mySubKey13: ["Value 3-3-1", "Value 3-3-2"],
},
myKey2: [
{
mySubKey21: "Value 4-1",
mySubKey22: "Value 4-2",
mySubKey23: ["Value 4-3-1", "Value 4-3-2"],
},
],
myKey3: ["Value 5-1", "Value 5-2"],
myIgnoredKey1: { myIgnoredKey11: "Ignored value 1", "my-ignored-key=12": "Ignored value 2" },
};

const formattedData = transformKeys(data, snakeCase, ["myIgnoredKey1"]);

expect(formattedData).eql({
key1: "Value 1",
key2: { key21: "Value 2" },
my_key1: {
my_sub_key11: "Value 3-1",
my_sub_key12: "Value 3-2",
my_sub_key13: ["Value 3-3-1", "Value 3-3-2"],
},
my_key2: [
{
my_sub_key21: "Value 4-1",
my_sub_key22: "Value 4-2",
my_sub_key23: ["Value 4-3-1", "Value 4-3-2"],
},
],
my_key3: ["Value 5-1", "Value 5-2"],
myIgnoredKey1: {
myIgnoredKey11: "Ignored value 1",
"my-ignored-key=12": "Ignored value 2",
},
});
});
});

0 comments on commit f58865e

Please sign in to comment.