Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create property on string

Tags:

javascript

I have stumbled on a weird issue when trying to recursively set properties on an empty object with the following code:

Simplified code

const birthdays = {};

// Loop -> Passing day, id and birthday
birthdays[day] = day;
birthdays[day][id] = birthday;

Example of day: '01012017'

Example of id: 1547

Example of birthday: {name: John}

Error message

Cannot create property '123' on string '06012017'

I saw some people with Angular having this issue but their answer don't solve anything for me (as is angular specific syntax etc).

like image 384
NealVDV Avatar asked Jan 06 '17 16:01

NealVDV


2 Answers

Empty Objects need to be individually created before their values are assigned. And use of const is not a good idea here, anyway, it's just my suggestion.

const birthdays = {};
var day = 123;
var id = 21;
var birthday = 2016;
// Loop -> Passing day, id and birthday
birthdays[day] = {};
birthdays[day][id] = birthday;
like image 101
Praveen Kumar Purushothaman Avatar answered Nov 14 '22 21:11

Praveen Kumar Purushothaman


I had a similar error message TypeError: Cannot create property 'false' on boolean 'false' in Node 14.3.0 (ES 2019), using the new Javascript semicolon-less syntax, with a variable declaration and assignment followed by a destructuring assignment on the next line.

The code that caused the error:

var a = b ()
[c, d] = e ()

Solved by:

var a = b ()
;
[c, d] = e ()
like image 25
gregn3 Avatar answered Nov 14 '22 23:11

gregn3