9

I used a literal as a dictionary, but a third party binding tool only takes arrays.

This is one way, is there a better one?

var arr = [];
$.each(objectLiteral, function () { arr.push(this); });
Jason Gennaro
  • 34,535
  • 8
  • 65
  • 86
Anders
  • 17,306
  • 10
  • 76
  • 144

5 Answers5

9

I think there is nothing wrong with your solution.

This is a shorter one:

var arr = $.map(objectLiteral, function (value) { return value; });
KARASZI István
  • 30,900
  • 8
  • 101
  • 128
8

Your method is fine, clear and readable. To do it without jQuery, use the for (..in..) syntax:

var arr = [];
for (prop in objectLiteral) {
  arr.push(objectLiteral[prop]);
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
3

In vanilla JS...

If we want to convert an object literal

var obj = {
 species: 'canine',
 name: 'Charlie',
 age: 4
}

into an array of arrays

[['species', 'canine'], ['name', 'Charlie'], ['age', 4]]

here is one way

function objToArr(obj){
  var arr = [];

  for (var key in obj){
    arr.push([key, obj[key]]);
  }
  return arr;
}
nSideOut
  • 29
  • 2
3
const objectLiteral = { hell: 'devil' };

const ver1 = Object.keys(objectLiteral); // ['hell']
const ver2 = Object.values(objectLiteral); // ['devil']
const ver3 = Object.entries(objectLiteral); // [['hell', 'devil']]

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

basickarl
  • 37,187
  • 64
  • 214
  • 335
0

In ES2017 you can now use Object.entries and with ES6 destructuring support you can use the resulting array pretty nice, example

Object.entries(objectLiteral).filter(([key, value]) => !!value).map(([key, value]) => key)

Gets you all properties with a value

Anders
  • 17,306
  • 10
  • 76
  • 144