return object if array contains one item or return array if multiple in javascript

You can achieve this by using conditional statements to check the length of the array. If the length is one, then you can return the object inside the array. If the length is greater than one, you can return the array itself.

Here's an example code block:

index.tsx
function getObjectOrArray(arr) {
  if (arr.length === 1) {
    return arr[0]; // return the object if array contains one item
  } else {
    return arr; // return the array if it contains multiple items
  }
}

// example usage
const arr1 = [{name: 'John', age: 28}];
const arr2 = [{name: 'Mary', age: 23}, {name: 'Alex', age: 31}];

console.log(getObjectOrArray(arr1)); // {name: 'John', age: 28}
console.log(getObjectOrArray(arr2)); // [{name: 'Mary', age: 23}, {name: 'Alex', age: 31}]
488 chars
15 lines

In the above code block, the getObjectOrArray function takes an array as an argument. It then checks if the length of the array is equal to one using the if statement. If it is, then it returns the object inside the array. Otherwise, it returns the array itself using the else statement.

Hope this helps!

gistlibby LogSnag