user6438693
user6438693

Reputation:

Better way to create an object into array in javascript?

I have an object/array statements and when it is not an array i want to make it to an array, what i try is as follows:

var statements = policy_blob['Statement'];
if(!$.isArray(statements)) {
  var statements_ = statements;
  statements = []
  statements[0] = statements_;
}

It is working fine for me but i am looking for the better alternative. Can anyone help me on this.

Upvotes: 0

Views: 50

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

You can do it in a single line using ternary syntax.

var statements = $.isArray(policy_blob['Statement']) ? policy_blob['Statement'] : [policy_blob['Statement']];

Or do it after caching in a variable.

var statements = policy_blob['Statement'];
statements = $.isArray(statements) ? statements : [statements];

// or using Short-circuit evaluation property of `||`(logical or)
var statements = policy_blob['Statement'];
$.isArray(statements) || statements = [statements];

Refer : Ternary operator, Short-circuit evaluation

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074385

You can do it all at once:

statements = [statements];

e.g.:

var statements = policy_blob['Statement'];
if(!$.isArray(statements)) {
    statements = [statements];
}

The right-hand side is evaluated before being assigned to the left-hand side, there's no problem with having the same variable on both sides of it.

Live example:

var policy_blob = {
  Statement: 42
};
var statements = policy_blob['Statement'];
if(!$.isArray(statements)) {
    statements = [statements];
}
console.log(statements);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions