简体   繁体   中英

Automatically return first item of an array if there is only one

Is there a way to return automatically the first object of an array is there is only one inside, without using an if condition?

Basically what I'm doing right know is

if (isNestedElement) {
    return generatedElement;
} else if (generatedElement.length === 1) {
    return generatedElement[0];
}

And I'm trying to simplify it like

if (isNestedElement) {
    return generatedElement;
}

But the second return must be and object when there is only 1 object inside the array.

I don't know anything to do it simply in JavaScript, any idea?

Examples

If my array is looking like

[
   {foo: foo, bar: bar},
   {two: two, three: three},
   {four: four, baz: baz},
   {five: five},
]

I want to return

[
   {foo: foo, bar: bar},
   {two: two, three: three},
   {four: four, baz: baz},
   {five: five},
]

By when my array is looking like

[
   {foo: foo, bar: bar},
]

I want to return

{foo: foo, bar: bar}

You can use Conditional (ternary) operator :

if (isNestedElement) {
  return generatedElement.length === 1? generatedElement[0] : generatedElement;
}

You could use a conditional (ternary) operator ?: and check for the length of the array.

return generatedElement.length === 1
    ? generatedElement[0]
    : generatedElement;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM