0

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 .

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.