简体   繁体   English

lodash的mapValues适用于所有键

[英]lodash's mapValues for all keys

I'm trying to use lodash in the most elegant way possible to convert the following object: 我试图以最优雅的方式使用lodash来转换以下对象:

var original = {
  email: {
    0: 'user01@gmail.com',
    1: 'user02@gmail.com',
    2: 'user03@gmail.com'
  },
  name: {
    0: 'Sam',
    1: 'Jack',
    2: 'Lucy'
  },
  last_name: {
    0: 'Smith',
    1: 'Green',
    2: 'Tompson'
  }
};

Into this: 进入:

var expected = [
  {
    email: 'user01@gmail.com',
    name: 'Sam',
    last_name: 'Smith'
  },
  {
    email: 'user02@gmail.com',
    name: 'Jack',
    last_name: 'Green'
  },
  {
    email: 'user03@gmail.com',
    name: 'Lucy',
    last_name: 'Tompson'
  }
];

I know I can use _.mapValues(original, index); 我知道我可以使用_.mapValues(original, index); where index is either 0 , 1 or 2 , but I need an array with all mapValues. 其中index是要么012 ,但我需要与所有mapValues阵列。

The keys in original are variable (sometimes there are 3, sometimes there are 2, sometimes 6) as are the number of indexes. original中的键是可变的(有时有3个,有时有2个,有时是6个),索引的数量也是如此。 I've found a few solutions, but they all seem too convoluted. 我找到了一些解决方案,但它们看起来都太复杂了。 I have a feeling there's an elegant way of doing this with a few lodash's methods. 我有一种感觉,用一些lodash的方法做到这一点很优雅。 Any help would be appreciated. 任何帮助,将不胜感激。

How about this: 这个怎么样:

// _.size(_.values(original)[0]) - amount of rows (3 in that case)
var expected = _.times(_.size(_.values(original)[0]), function (index) {
    return _.mapValues(original, index);
});

Edit : one line 编辑 :一行

var expected = _.times(_.size(_.values(original)[0]), _.mapValues.bind(_, original));

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

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