本文介绍了创建具有特定键的对象数组,然后从对象中删除该键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用lodash从特定键创建对象数组,然后从其对象中删除此给定键.
I have used lodash to create an array of objects from a specific key, then remove this given key from its object.
我有这个
var cars = [{
"itemID": "-KUsw42xU-S1qA-y3TiI", // use this as key
"name": "Car One",
"qtd": "1"
},
{
"itemID": "-KUsw42xU-r1qA-s3TbI",
"name": "Car Two",
"qtd": "2"
}
]
试图得到这个:
var cars = {
"-KUsw42xU-S1qA-y3TiI": {
"name": "Car One",
"qtd": "1"
},
"-KUsw42xU-r1qA-s3TbI": {
"name": "Car Two",
"qtd": "1"
}
}
我尝试过这种方法,但是没有成功.
I have tried this approach, but I have no success.
_.chain(a)
.keyBy('itemID')
.omit(['itemID'])
.value();
推荐答案
您快到了.要从每个对象中省略itemID,您需要映射值(使用 mapValues ):
You were nearly there. To omit the itemID from each object you need to map the values (using mapValues):
var result = _.chain(cars)
.keyBy('itemID')
.mapValues( v => _.omit(v, 'itemID'))
.value();
这篇关于创建具有特定键的对象数组,然后从对象中删除该键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!