Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How might I extract the property values of a JavaScript object into an array?

Given a JavaScript object:

var dataObject = {    object1: {id: 1, name: "Fred"},     object2: {id: 2, name: "Wilma"},     object3: {id: 3, name: "Pebbles"} }; 

How do I efficiently extract the inner objects into an array? I do not need to maintain a handle on the object[n] IDs.

var dataArray = [     {id: 1, name: "Fred"},      {id: 2, name: "Wilma"},      {id: 3, name: "Pebbles"}] 
like image 448
Matt Norris Avatar asked Nov 11 '09 23:11

Matt Norris


People also ask

Can we convert object to array in JavaScript?

To convert an object into an array in Javascript, you can use different types of methods. Some of the methods are Object. keys(), Object. values(),and Object.

How do you create an array of values from an object?

You can convert its values to an array by doing: var array = Object. keys(obj) . map(function(key) { return obj[key]; }); console.

How do you find the value of an object in an array?

To get the values of an object as an array, use the Object. values() method, passing it the object as a parameter. The method returns an array containing the object's property values in the same order as provided by a for ... in loop. Copied!


1 Answers

var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]}); 
like image 167
Anonymous Avatar answered Oct 20 '22 21:10

Anonymous