IsaacWIvins
IsaacWIvins

Reputation: 15

How to turn an object into multiple key-value arrays

I have the variables in place and onclick function set up but I can't figure out how to turn this object into an array within an array. I'm trying to turn this

{"Wins":30,"Losses:"32}

into this:

[["Wins:",30]["Losses:",32]]

So I can append it to the data.addRows:

      var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Total: ');
        data.addRows([
          ['String', number],
          ['String', number],
        ]);

Upvotes: 0

Views: 77

Answers (5)

kind user
kind user

Reputation: 41893

I suggest you to use following approach:

var obj = {"Wins": 30, "Losses": 32};
    console.log(Object.keys(obj).map(v => [v + ':', obj[v]]));

Upvotes: 1

gyre
gyre

Reputation: 16777

In the latest releases of some browsers, you can use the new Object.entries to do this:

(Credit to georg for mentioning this first in the comments above.)

var data = {
  "Wins": 30,
  "Losses": 32
}

console.log(
  Object.entries(data) //=> [ ['Wins', 30], ['Losses', 32] ]
)

However, you can also use the better-supported Object.keys and Array#map to create your own entries function:

var data = {
  "Wins": 30,
  "Losses": 32
}

function entries (object) {
  return Object.keys(data).map(function (k) { return [k, this[k]] }, data)
}

console.log(
  entries(data) //=> [ ['Wins', 30], ['Losses', 32] ]
)

Upvotes: 1

Mert Akcakaya
Mert Akcakaya

Reputation: 3129

Following code stores each pair in an array:

var obj = { 'Wins': 30, 'Losses': 32 };
var keyvalues = [];
for (var prop in obj) {
    keyvalues.push([prop, obj[prop]]);
}

Upvotes: 0

Sandeep Thar
Sandeep Thar

Reputation: 1177

pure javascript

var myObject={"Wins":30,"Losses":32};
var resultArray=[];
for(var key in myObject) {
    if(myObject.hasOwnProperty(key)) {
        resultArray.push([key,myObject[key]])
    }
}
console.log(resultArray)

Result [["Wins", 30], ["Losses", 32]]

Upvotes: 0

bejado
bejado

Reputation: 1460

Object.entries() is great, but there is no IE support. Since you're using jQuery, you can se jQuery.map.

var myObj = {"Wins": 30,"Losses": 32};
var array = $.map(myObj, function(value, index) {
    return [[index, value]];
});
console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Related Questions