简体   繁体   中英

How to convert an object to array with correct data types in vanilla Javascript?

Trying to take an object like:

var object = {name: joe, age: 23, student: true}

I need to convert this to an array like:

["joe", 23, true]

Since objects treat all properties as strings, how do I format them properly for an array? The function also has to be dynamic, not hard coded object.

Use object values:

 var object = {name: "joe", age: 23, student: true} console.log(Object.values(object)); 

Although Object.values() will do the trick for you.Another way to do it is using Array.prototype.map()

 var obj = { name: 'joe', age: 23, student: true }; const result = Object.keys(obj).map((elm) => obj[elm]); console.log(result); 

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