8

I am converting an object into an array. The keys of the object contain names such as "cool", as can be seen below:

var obj = {
  "cool": "Mustang",
  "family": "Station Wagon",
  "small": {
    0: "small car 1",
    1: "small car 2"
  }
};

When converting, the returned array looks as followed:

Array[3]
0:"Mustang"
1:"Station Wagon"
2:Object
    0:"small car 1" 
    1:"small car 2"

As you can see in the array above the names of keys from the object such as "cool" are lost, instead they are replaced with numbers. Furthermore, the array contains an object, I would like this object to be an array within the array.

I would like the returned array to be like this instead:

Array[3]
"cool":"Mustang"
"family":"Station Wagon"
"small": Array[2]
    0:"small car 1" 
    1:"small car 2"

I would very much appreciate your help. A fiddle with the code can be found here: https://jsfiddle.net/v02q4sy2/8/

var obj = {"cool":"Mustang","family":"Station Wagon","small":{0:"small car 1",1:"small car 2"}}

var arr = $.map(obj, function(value, index) {
    return [value];
});

console.log(arr);
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
user3398797
  • 429
  • 1
  • 7
  • 16

2 Answers2

13

Based on the code that you provided, it looks like you would just need to return an object within the map method containing the corresponding key/value pair:

Updated Example

var arr = $.map(obj, function(value, key) {
  return { [key]: value };
});

You don't need jQuery for this though. Here is a simple example with plain JavaScript utilizing the native .map() method along with Object.keys() to retrieve a mappable array of keys from the object:

Updated Example

var arr = Object.keys(obj).map(function (key) {
  return { [key]: obj[key] };
});
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • @juanpscotto - That's one way to dynamically set the key/value pair of an object. If the brackets `[key]` weren't used like `key: obj[key]`, then the key would be a string `'key'` rather than whatever dynamic key value was passed. – Josh Crozier Dec 04 '17 at 15:28
  • This does not give the same result as he wants. It returns objects, he wants arrays. – MrEduar Jun 19 '20 at 21:36
3

If you're in an environment where you can use the latest JavaScript features, this is pretty easy with Object.entries.

var obj = {"cool":"Mustang","family":"Station Wagon","small":{0:"small car 1",1:"small car 2"}}

var arr = Object.entries(obj);

console.log(arr);

https://jsfiddle.net/eszfLj17/1/

Object.entries()

Tom Coughlin
  • 453
  • 3
  • 13