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"}]
Using underscore:
With jQuery, you can do it like this -
Demo
[It turns out my answer is similar to @Anonymous, but I keep my answer here since it explains how I got my answer].
The original object has THREE properties (i.e. 3 keys and 3 values). This suggest we should be using
Object.keys()
to transform it to an array with 3 values.We now have 3 values, but not the 3 values we're after. So, this suggest we should use
Array.prototype.map()
.Using the accepted answer and knowing that Object.values() is proposed in ECMAScript 2017 Draft you can extend Object with method: