Is there a way to shorten or refactor this longVersion() function below? Any ideas is appreciated. Thanks!
https://replit.com/talk/share/convert-obj-to-ary/137799
const person = {
name: 'Juan De la Cruz',
job: 'Programmer',
}
function longVersion(person) {
let aryPerson = []
if (Array.isArray(person) && person.length > 0) {
aryPerson = person
} else {
aryPerson.push(person)
}
return aryPerson
}
const result = longVersion(person)
console.log('longVersion:', result)
//output: longVersion: [ { name: 'Juan De la Cruz', job: 'Programmer' } ]
asked Apr 28, 2021 at 10:41
Arman O
3,1231 gold badge35 silver badges33 bronze badges
-
So, if your input is an object, you want an array containing that object out, and if it's an array, you want just that array out?Cerbrus– Cerbrus2021年04月28日 10:42:24 +00:00Commented Apr 28, 2021 at 10:42
-
2Pretty sure this belongs on codereview.stackexchange.comDane Brouwer– Dane Brouwer2021年04月28日 10:49:12 +00:00Commented Apr 28, 2021 at 10:49
-
Thanks for sharing the links sir.Arman O– Arman O2021年04月28日 10:52:20 +00:00Commented Apr 28, 2021 at 10:52
1 Answer 1
If all you want to do is convert the input to an array, if it isn't already an array, then this is enough:
const person = { name: 'Juan De la Cruz', job: 'Programmer' };
function toArray(person) {
return Array.isArray(person) ? person : [person];
}
const result = toArray(person);
console.log('toArray:', result);
answered Apr 28, 2021 at 10:44
Cerbrus
73.3k19 gold badges138 silver badges151 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Arman O
Hmm, this is nice. Thanks
lang-js