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?
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'
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With