Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an object in json format

In my node (express) app, I want to send a json response back to the client. It would look something like this.

{"someTshirt": 
      {small : 'available'},
      {med : 'available'},
      {large : 'not available'}
 }

I'd reiterate through the sizes and append to the response set with its availability. How would I create this object to begin with in plain javascript within app.js? how would I add the 'someTshirtName' to the beginning of this object as well as appending each size's availability to it after the object has been created?

like image 996
archytect Avatar asked Feb 21 '26 21:02

archytect


2 Answers

You can build your object like this:

var availability = {"someTshirt": 
    {
        'small': 'available',
        'med' : 'available',
        'large' : 'not available'
    }
};

Then you can access this object with:

availability.someTshirt.small
>>> 'available'
availability.someTshirt.large
>>> 'not available'

However I'd recommend you to use booleans instead of strings, which are easier to manipulate. You can still change the display string later:

var availability = {"someTshirt": 
    {
        'small': true,
        'med' : true,
        'large' : false
    }
};

if (availability.someTshirt.small) {
    console.log('available');
}
>>> 'available'

[edit] Response to the comment:

If you want to create your objects dynamically, you can do the following:

var availability = {};
availability.someTshirt = {};
availability.someTshirt.small = true;
availability.someTshirt.med = true;
availability.someTshirt.large = false;

if (availability.someTshirt.small) {
    console.log("available");
} else {
    console.log("not available");
}
>>> 'available'

availability.someTshirt.small = false;

if (availability.someTshirt.small) {
    console.log("available");
} else {
    console.log("not available");
}
>>> 'not available'
like image 111
Thierry J. Avatar answered Feb 24 '26 11:02

Thierry J.


If you need to build your object based on JSON string returned to your code, you can use eval statement. for example you have a string variable sJsonResult containing your JSON response. Your code can go something like;

var sJsonResult = "{someTshirt: {small : 'available', med : 'available',large : 'not available'}}";

var o;

eval("o = " + sJsonResult);

alert(o.someTshirt.small);
like image 25
Yuriy Galanter Avatar answered Feb 24 '26 11:02

Yuriy Galanter