user3004356
user3004356

Reputation: 880

How to check whether an array contains elements and form json accordingly

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

Answers (4)

Johan
Johan

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

user2575725
user2575725

Reputation:

Try this one:

var json2 = JSON.stringify( { "dataList": (values2.length ? values2 : null) });

Upvotes: 0

Marwen Cherif
Marwen Cherif

Reputation: 560

Just like this :

    var json2 = values2.length > 0 ? JSON.stringify( { "dataList":values2})
                : JSON.stringify( { "dataList": null}) ;

Upvotes: 0

rmuller
rmuller

Reputation: 1837

check for its length and based on that create an if/else.

Upvotes: 0

Related Questions