繁体   English   中英

Javascript强调数组到对象

[英]Javascript underscore array to object

是否有一种简单/干净的方式使用Underscore来解决这个问题

[ { id: 'medium', votes: 7 },
  { id: 'low',    votes: 9 },
  { id: 'high',   votes: 5 } ]

 { 'low'    : 9,
   'medium' : 7,
   'high'   : 5 }

你可以考虑_.indexBy(...)

var data = [{
    id: 1,
    name: 'Jon Doe',
    birthdate: '1/1/1991',
    height: '5 11'
}, {
    id: 2,
    name: 'Jane Smith',
    birthdate: '1/1/1981',
    height: '5 6'
}, {
    id: 3,
    name: 'Rockin Joe',
    birthdate: '4/4/1994',
    height: '6 1'
}, {
    id: 4,
    name: 'Jane Blane',
    birthdate: '1/1/1971',
    height: '5 9'
}, ];

var transformed = _.indexBy(data, 'id');

这是一个小提琴: https//jsfiddle.net/4vyLtcrf/3/

更新:在Lodash 4.0.1中,方法_.indexBy已重命名为_.keyBy

var data = [ { id: 'medium', votes: 7 },
  { id: 'low',    votes: 9 },
  { id: 'high',   votes: 5 } ];

您可以使用_.map_.values_.object这样做

console.log(_.object(_.map(data, _.values)));
# { medium: 7, low: 9, high: 5 }

说明

我们使用map函数将values函数(它获取给定对象的所有值)应用于data所有元素,这将给出

# [ [ 'medium', 7 ], [ 'low', 9 ], [ 'high', 5 ] ]

然后我们使用object函数将其转换为对象。

这是与香草js:

var result = {};
[ { id: 'medium', votes: 7 },
  { id: 'low',    votes: 9 },
  { id: 'high',   votes: 5 } ].forEach(function(obj) {
    result[obj.id] = obj.votes;
});
console.log(result);

对我来说更简单: each

   var t = {};
   _.each(x, function(e){
     t[e.id] = e.votes;
   });
//--> {medium: 7, low: 9, high: 5}

最强大的下划线方法是减少。 你几乎可以做任何事情。 更大的好处是你只需要在ONCE上迭代!

var array = [ 
    { id: 'medium', votes: 7 },
    { id: 'low',    votes: 9 },
    { id: 'high',   votes: 5 } 
];
var object = _.reduce(array, function(_object, item) { 
    _object[item.id] = item.votes; 
    return _object; 
}, {});

运行后,对象将是:

{
  medium:7,
  low:9,
  high:5
}

使用indexBy

_.indexBy([ 
   { id: 'medium', votes: 7 },
   { id: 'low',    votes: 9 },
   { id: 'high',   votes: 5 } 
 ], 'id');

我知道这是一个旧帖子,但您可以使用_.reduce以干净的方式进行转换

var data = [
    { id: 'medium', votes: 7 },
    { id: 'low',    votes: 9 },
    { id: 'high',   votes: 5 }
]

var output = _.reduce(data, function(memo, entry) {
    memo[entry.id] = entry.votes;
    return memo;
}, {});

console.log(output);

您可以使用本机JS Array.reduce执行此操作

const myArray = [ { id: 'medium', votes: 7 },
{ id: 'low',    votes: 9 },
{ id: 'high',   votes: 5 } ]

const myObject = myArray.reduce((obj, item)=>{
  o[item.id] = item.votes
  return o
}, {})

有关详细信息,请查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM