Reputation: 880
I have an array which is converted to JSON. I want to check if there are any elements in the array, if there are any elements then it should form JSON and if there aren't any then it should store NULL.
var json2 = JSON.stringify( { "dataList": values2});
where values2 is an array
How can I make this.
Upvotes: 0
Views: 90
Reputation: 35213
Like this?
var json2 = values2.length > 0 ? JSON.stringify({ "dataList": values2 }) : null;
Or if you want the dataList
property to be null:
var dataList = values2.length > 0 ? values2 : null,
json2 = JSON.stringify({ "dataList": dataList });
If you want to check if the array has one empty string value, the condition should be:
values2.length > 0 && !(values2.length === 1 && values2[0] === '')
Upvotes: 1
Reputation:
Try this one:
var json2 = JSON.stringify( { "dataList": (values2.length ? values2 : null) });
Upvotes: 0
Reputation: 560
Just like this :
var json2 = values2.length > 0 ? JSON.stringify( { "dataList":values2})
: JSON.stringify( { "dataList": null}) ;
Upvotes: 0