使用下划线将对象键值转换为数组

时间:2017-01-08 14:49:48

标签: underscore.js

我有以下对象

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

我希望得到:

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

我怎样才能使用下划线

谢谢。

3 个答案:

答案 0 :(得分:2)

你可以不用下划线来做到这一点:

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)

如果你已经使用下划线,我推荐Gruff Bunny的答案,它更短。

答案 1 :(得分:1)

使用下划线的pairs功能:

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

答案 2 :(得分:0)

你可以不用下划线来做。

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

使用下划线的版本

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