从对象创建新集合的功能方法是什么?

时间:2019-02-27 01:58:18

标签: javascript lodash

从这个不会变异的对象创建这个集合的方法是什么。我可以使用lodash吗?

var obj = {Express: 2, Long_Haul: 1, Short_Haul: 1}

let collection = []

Object.keys(obj).forEach(key => collection.push({method: key, quantity: 
obj[key]}))

// output:
// [ { method: 'Express', quantity: 2 },{ method: 'Long_Haul', quantity: 1 },{ method: 'Short_Haul', quantity: 1 } ]

4 个答案:

答案 0 :(得分:5)

使用.map将对象.entries的数组转换为具有所需属性名称的对象的数组:

var obj = {Express: 2, Long_Haul: 1, Short_Haul: 1}
const collection = Object.entries(obj)
  .map(([method, quantity]) => ({ method, quantity }));
console.log(collection);

虽然您可以 使用Lodash来实现此目的,但是并不需要它,内置方法可以正常工作。

答案 1 :(得分:1)

您可以使用js中的内置功能,如果您使用的js引擎不提供这些功能,则可以使用lodash。

let obj = {Express: 2, Long_Haul: 1, Short_Haul: 1}
let collection = _.map(_.toPairs(obj), function(arr) {
  return { method: arr[0], quantity: arr[1] };
});

console.log(collection);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

答案 2 :(得分:1)

这是lodash中的一个解决方案,它使用toPairsmap链和部分应用的zipObject链。

const collection = _(obj).toPairs()
    .map(_.partial(_.zipObject, ['method', 'quantity']))
    .value();

var obj = {Express: 2, Long_Haul: 1, Short_Haul: 1};

const collection = _(obj).toPairs()
	.map(_.partial(_.zipObject, ['method', 'quantity']))
	.value();
  
console.log(collection);
.as-console-wrapper{min-height:100%; top: 0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 3 :(得分:0)

这是使用lodash的解决方案

const obj = {Express: 2, Long_Haul: 1, Short_Haul: 1}
const collection = _.map(obj, (value, key) => ({method: key, quantity: value}))

map 函数将使用 key 调用 iteratee 。使用一个_.map函数即可完成工作。

  

_.map(collection, [iteratee=_.identity])

     
    

通过运行iteratee中的集合中的每个元素来创建值数组。使用三个参数调用iteratee:     (值,索引|键,集合)。

  
     

https://lodash.com/docs/4.17.11#map