我有一个像这样的对象
data: [
{
"Type":"100, S4",
"Model":"1 serie, e82",
"Manufacturer":"BMW",
"Vehicle":"Cars"
},
{
"Type":"type 2",
"Model":"a serie",
"Manufacturer":"Toyota",
"Vehicle":"Cars"
},
{
"Type":"type 3",
"Model":"v4",
"Manufacturer":"Toyota",
"Vehicle":"SUVs"
}
]
然后我使用了jquery和lodash库,期望从对象中返回不同的值。
尝试过#1:
$.each( data, function( i, value ) {
var vehicles = _.uniqBy(value);
console.log(vehicles);
});
结果:在console.log中打印了3个空数组
尝试#2:
$.each( data, function( i, value ) {
var vehicles = _.uniqBy(value.Vehicle);
console.log(vehicles);
});
结果:拆分字符中的4个数组
(4) ["C", "a", "r", "s"]
(4) ["C", "a", "r", "s"]
(4) ["S", "U", "V", "s"]
我希望在
中有一个数组["Cars", "SUVs"]
我怎么处理它?谢谢你的帮助!
答案 0 :(得分:1)
试试这个
var vehicles = _.uniqBy(data, function (e) {
return e.Vehicle;
}).map(function(veh){
return veh.Vehicle;
});
console.log(vehicles);
答案 1 :(得分:1)
您可以使用lodash#map
获取所有Vehicle
属性字符串,然后使用lodash#uniq
删除所有重复的字符串。
var result = _(data).map('Vehicle').uniq().value();
var data = [
{
"Type":"100, S4",
"Model":"1 serie, e82",
"Manufacturer":"BMW",
"Vehicle":"Cars"
},
{
"Type":"type 2",
"Model":"a serie",
"Manufacturer":"Toyota",
"Vehicle":"Cars"
},
{
"Type":"type 3",
"Model":"v4",
"Manufacturer":"Toyota",
"Vehicle":"SUVs"
}
];
var result = _(data).map('Vehicle').uniq().value();
console.log(result);

body > div { top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;