mariocasciaro / object-path

A tiny JavaScript utility to access deep properties using a path (for Node and the Browser)
MIT License
1.06k stars 84 forks source link

Cannot set object with number in path e.g. 'a.2008' #95

Closed aldo-sanchez closed 1 year ago

aldo-sanchez commented 6 years ago

I want to set an object as follows:

let emptyObj = {}
const path = 'a.2008'
const value = [1,2,3,4]
objectPath.set(emptyObj, path, value)

I expect the object to look like:

emptyObject = {
  a: {
    2008: [1, 2, 3, 4],
  }
}

Instead the object looks like this:

{
    "a": [
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        ...(2008x),
       [1, 2, 3, 4]
    ],
}
pocesar commented 6 years ago

use an array path when you expect no conversions. by convention, when there's a number in a string path, it always mean an array index. so in your example:

let emptyObj = {}
const path = ['a', '2008'] // string '2008' really means string, thus an object property
const value = [1,2,3,4]
objectPath.set(emptyObj, path, value)