Ranjith
Ranjith

Reputation: 2819

JS - how to append child into an object

For example,

This is my object creation

var myObj = {};

If I want to add value in my object, i'm doing this way.

myObj.name = 'User1';
myObj.role = 'CEO';

This is fine. For my node.js project scenario, I need to pass level.type string object into myObj.

In clearly like this,

myObj.level.type = 'Level 1';

How to I append level.type named object values into myObj?

I don't think this is may confused you. I need my object values like this,

 {
  "name": "User1",
  "role": "CEO",
  "level.type": "Level 1"
 }

Upvotes: 1

Views: 106

Answers (3)

KooiInc
KooiInc

Reputation: 122888

The child object has to be created first:

myObj.level = {};
myObj.level.type = 'Level 1';

Or shorter:

myObj.level = {type: 'Level 1'};

or indeed if there is a chance level was already a child of myObj:

myObj.level = myObj.level || {type: 'Level 1'};

In sum you can create myObj like this:

var myObj = {
 name: 'User1',
 role: 'CEO',
 level: {type: 'Level 1'}
};

And to address your 'misleading':

var myObj = {
 name: 'User1',
 role: 'CEO',
 'level.type': 'Level 1'
};

Upvotes: 5

ffflabs
ffflabs

Reputation: 17481

When appending a subproperty, you just need to check if it's already set and if it isn't, do it .

myObj.level = myObj.level || {};
myObj.level.type = 'Level 1';

That will prevent resetting myObj.level if it's already set.

Edit

If you need to pass a property name which has a dot in it, you must quote it and use bracket notation

myObj['level.type'] = 'Level 1';

same goes for any property name that has special characters in it (- + etc). Key names are stored as strings internally so as long as they are quoted you don't need to fear implicit evaluations.

Upvotes: 6

iddqd
iddqd

Reputation: 1305

myObj.level is undefined at first you need to init myObj.level as an object:

myObj.level = {type: 'Level 1'}

Upvotes: 0

Related Questions