Alexander Zeitler
Alexander Zeitler

Reputation: 13109

Javascript create array of Object property values

Given this Object in Javascript

{
  "0": "hello",
  "1": { text: "world" }
}

What's the shortest way to create this array from that object?

[
  "hello",
  { text: "world" }
]

I've seen somebody using Array.prototype.splice(theObject) but it doesn't seem to work for me.

Update:

  1. Order of output needs to be guaranteed
  2. 0 and 1 can be any arbitrary string value and the order at property level needs to be maintained in the corresponding array.
  3. Needs to work with Node.js 6

Upvotes: 4

Views: 83

Answers (5)

Pointy
Pointy

Reputation: 413757

If you want to be sure that the original keys of the object correspond to the positions in the resulting array, you can't rely on Object.values() or a for ... in loop. You can use Object.keys() and sort that array.

var keys = Object.keys(yourObject);
keys.sort();
var array = keys.map(key => yourObject[key]);

Now understand that the call to .sort() can include a comparator function to impose any ordering desired on the original object keys. The sample in the OP is very simple, and the above would work. However more complicated keys might require a custom comparator.

Upvotes: 2

OliverRadini
OliverRadini

Reputation: 6466

This should maintain the order based on the keys, including where keys have more than one digit

const test = {
  "0": "hello",
  "3": "three",
  "1": { text: "world" },
  "2": "two",
  "11": "eleven",
}

const transform = obj => Object.keys(obj)
  .sort((a, b) => parseInt(a) > parseInt(b) ? 1 : -1)
  .map(key => obj[key])
  
 console.dir(transform(test))

Upvotes: 1

Youssef
Youssef

Reputation: 110

Try using for..in loop like this:

let obj = {
  "0": "hello",
  "1": { text: "world" }
   }
  let result = []
  for(var value in obj){
     result.push(obj[value])
   }

Upvotes: 0

Steven Spungin
Steven Spungin

Reputation: 29109

let src = {
  "0": "hello",
  "1": {
    text: "world"
  }
}

let res = [src].map(it => [it['0'], it['1']])

console.log(res)

Upvotes: 0

Faly
Faly

Reputation: 13356

Just use Object.values:

console.log(Object.values({
  "0": "hello",
  "1": { text: "world" }
}));

Upvotes: 4

Related Questions