0

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.

1
  • Array [] or object {}? Commented Sep 19, 2017 at 15:40

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

True, and the duplicated property lookup won't make any difference basically ever.
Thanks @Pranav for saving my time :)
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.