From e5252cc1dc8c00b0ab73d85bec028d2c5f0fa761 Mon Sep 17 00:00:00 2001 From: Nikaple Date: Mon, 23 Oct 2023 17:06:39 +0800 Subject: [PATCH] fix: object keys which starts with a number --- src/flatten.test.ts | 2 ++ src/flatten.ts | 2 +- src/internal.test.ts | 5 +++++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/flatten.test.ts b/src/flatten.test.ts index 4972813..09e5d06 100644 --- a/src/flatten.test.ts +++ b/src/flatten.test.ts @@ -19,6 +19,7 @@ describe('flattenObject', () => { a: { b: { c: 123, + '2c': 456, }, d: [ { @@ -29,6 +30,7 @@ describe('flattenObject', () => { }, { 'a.b.c': 123, + 'a.b["2c"]': 456, 'a.d[0].e': 456, }, ); diff --git a/src/flatten.ts b/src/flatten.ts index 421099a..ed70029 100644 --- a/src/flatten.ts +++ b/src/flatten.ts @@ -26,7 +26,7 @@ export const flatten = ( const getKey = (key: string, prefix: string, isNumber: boolean) => { let k; if ( - /[.'"\s\\\b\f\n\r\t\v{}()[\];,<>=!+\-*%&|^~?:]/.test(key) || + /[.'"\s\\\b\f\n\r\t\v{}()[\];,<>=!+\-*%&|^~?:]|^\d+\D/.test(key) || key === '' ) { // use brackets if key contains special characters diff --git a/src/internal.test.ts b/src/internal.test.ts index 92b95df..0973cbe 100644 --- a/src/internal.test.ts +++ b/src/internal.test.ts @@ -7,6 +7,11 @@ describe('parsePath', () => { expect(result).toEqual(['foo', 'bar', 1, 'baz', 'qux']); }); + it('should parse string starts with number', () => { + const result = parsePath('foo.1bc'); + expect(result).toEqual(['foo', '1bc']); + }); + it('should parse escaped quotes correctly', () => { const result = parsePath('foo["bar\\"baz"]'); expect(result).toEqual(['foo', 'bar"baz']);