user6599525
user6599525

Reputation: 285

convert object key value to array using underscore

i have following object

           {Shanghai: 23.7,
            Lagos: 16.1,
            Istanbul: 14.2,
            Karachi: 14.0,
            Mumbai: 12.5,
            Moscow: 12.1,
            São Paulo:11.8}

and i want to get :

            [['Shanghai', 23.7],
            ['Lagos', 16.1],
            ['Istanbul', 14.2],
            ['Karachi', 14.0],
            ['Mumbai', 12.5],
            ['Moscow', 12.1],
            ['São Paulo', 11.8]]

how can i achive this using underscore

thanks .

Upvotes: 0

Views: 1475

Answers (3)

fafl
fafl

Reputation: 7385

You can do it without underscore:

var a = {Shanghai: 23.7, Lagos: 16.1, Istanbul: 14.2, Karachi: 14.0, Mumbai: 12.5, Moscow: 12.1, "São Paulo":11.8}

var b = Object.keys(a).map(k => [k, a[k]])
console.log(b)

I recommend the answer from Gruff Bunny if you already use underscore, it's shorter.

Upvotes: 2

Gruff Bunny
Gruff Bunny

Reputation: 27976

With underscore's pairs function:

var cities = {          
    Shanghai: 23.7,
    Lagos: 16.1,
    Istanbul: 14.2,
    Karachi: 14.0,
    Mumbai: 12.5,
    Moscow: 12.1,
    SãoPaulo:11.8
}

var result = _.pairs(cities);

Upvotes: 1

Sri
Sri

Reputation: 1336

You can do it without underscore.

var x = {Shanghai: 23.7, Lagos: 16.1, Istanbul: 14.2, Karachi: 14.0, Mumbai: 12.5, Moscow: 12.1, "São Paulo":11.8};
var y = [];
for (var city in x) {
  y.push([city, x[city]]);
}
console.log(y);

Version using underscore

var x = {Shanghai: 23.7, Lagos: 16.1, Istanbul: 14.2, Karachi: 14.0, Mumbai: 12.5, Moscow: 12.1, "São Paulo":11.8};
var y = _.map(x,function(city,num){
  return [city,num];
});
console.log(y);

Upvotes: 0

Related Questions