使用_.unique返回对象中的不同值时清空数组

时间:2017-05-25 10:25:18

标签: jquery lodash

我有一个像这样的对象

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"]

我怎么处理它?谢谢你的帮助!

2 个答案:

答案 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;
&#13;
&#13;