[javascript] 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"}]

This question is related to javascript arrays json

The answer is


[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.

var dataArray = Object.keys(dataObject);
// Gives: ["object1", "object2", "object3" ]

We now have 3 values, but not the 3 values we're after. So, this suggest we should use Array.prototype.map().

var dataArray = Object.keys(dataObject).map(function(e) { return dataObject[e]; } );
// Gives: [{"id":1,"name":"Fred"},{"id":2,"name":"Wilma"},{"id":3,"name":"Pebbles"}]

Maybe a bit verbose, but robust and fast

var result = [];
var keys = Object.keys(myObject);
for (var i = 0, len = keys.length; i < len; i++) {
    result.push(myObject[keys[i]]);
}

Using the accepted answer and knowing that Object.values() is proposed in ECMAScript 2017 Draft you can extend Object with method:

if(Object.values == null) {
    Object.values = function(obj) {
        var arr, o;
        arr = new Array();
        for(o in obj) { arr.push(obj[o]); }
        return arr;
    }
}

Using underscore:

var dataArray = _.values(dataObject);

Assuming your dataObject is defined the way you specified, you do this:

var dataArray = [];
for (var key in dataObject)
    dataArray.push(dataObject[key]);

And end up having dataArray populated with inner objects.


With jQuery, you can do it like this -

var dataArray = $.map(dataObject,function(v){
     return v;
});

Demo


Object.values() method is now supported. This will give you an array of values of an object.

Object.values(dataObject)

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values


ES6 version:

var dataArray = Object.keys(dataObject).map(val => dataObject[val]);

This one worked for me

var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});

var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});

ES2017 using Object.values:

_x000D_
_x000D_
const dataObject = {_x000D_
    object1: {_x000D_
        id: 1,_x000D_
        name: "Fred"_x000D_
    },_x000D_
    object2: {_x000D_
        id: 2,_x000D_
        name: "Wilma"_x000D_
    },_x000D_
    object3: {_x000D_
        id: 3,_x000D_
        name: "Pebbles"_x000D_
    }_x000D_
};_x000D_
_x000D_
const valuesOnly = Object.values(dataObject);_x000D_
_x000D_
console.log(valuesOnly)
_x000D_
_x000D_
_x000D_


In case you use d3. you can do d3.values(dataObject) which will give

enter image description here


I prefer to destruct object values into array:

[...Object.values(dataObject)]

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

var dataArray = [...Object.values(dataObject)];

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?