19 July 2024

In JavaScript, you can convert an object to an array in several ways depending on what part of the object you want to convert (keys, values, or entries). You can add a check to ensure that the variable is indeed an object before converting it to an array. In JavaScript, you can use the typeof operator to check the type, and the Array.isArray() method to ensure it's not an array. Here's how you can incorporate these checks into the previous examples.

Source code viewer
  1. const obj = { a: 1, b: 2, c: 3 };
  2.  
  3. if (typeof obj === 'object') {
  4. const valuesArray = Object.values(obj);
  5. console.log(valuesArray); // [1, 2, 3]
  6. }
Programming Language: ECMAScript