Reputation:
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
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
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