如何使用JavaScript从对象数组中获取键的唯一值?

时间:2018-12-11 08:36:11

标签: javascript arrays json object

我有一个像这样的json数据

{
  "name":"John",
  "age":30,
  "cars":"BMW"
},
{
  "name":"Micheal",
  "age":30,
  "cars":"Ford"
},
{
  "name":"Andy",
  "age":29,
  "cars":"Ford"
}

我只想在这样的数组中获得汽车的独特价值

cars = ["BMW, Ford"];

4 个答案:

答案 0 :(得分:1)

您可以使用Set作为唯一值。

var array = [{ name: "John", age: 30, car: "BMW" }, { name: "Micheal", age: 30, car: "Ford" }, { name: "Andy", age: 29, car: "Ford" }],
    cars = Array.from(new Set(array.map(({ car }) => car)));

console.log(cars);

答案 1 :(得分:0)

您需要使用Array.map()将每个对象映射到键cars并使用Array.filter()删除重复项

var cars = arr.map(ele => ele.cars).filter((ele, i, arr) => arr.indexOf(ele) == i);

var arr = [{
  "name":"John",
  "age":30,
  "cars":"BMW"
},
{
  "name":"Micheal",
  "age":30,
  "cars":"Ford"
},
{
  "name":"Andy",
  "age":29,
  "cars":"Ford"
}];

var cars = arr.map(ele => ele.cars).filter((ele, i, arr) => arr.indexOf(ele) == i);
console.log(cars);

您也可以使用ES5

var res = arr.map(function(ele){
  return ele.cars
}).filter(function(ele, i, arr){
  return arr.indexOf(ele) == i
});

答案 2 :(得分:0)

使用Array.map获取所有汽车价值,并使用Array.filter过滤重复的汽车价值,您可以通过链接Array.map().filter()

来实现

var arr = [{
    "name": "John",
    "age": 30,
    "cars": "BMW"
  },
  {
    "name": "Micheal",
    "age": 30,
    "cars": "Ford"
  },
  {
    "name": "Andy",
    "age": 29,
    "cars": "Ford"
  }
];

var carValues = arr.map( (value) => value.cars).filter( (value, index, _arr) => _arr.indexOf(value) == index);
console.log(carValues);

答案 3 :(得分:0)

假设数据是一个数组,只需像这样遍历该数组即可:

var arr = [{
  "name":"John",
  "age":30,
  "cars":"BMW"
},
{
  "name":"Micheal",
  "age":30,
  "cars":"Ford"
},
 {
  "name":"Andy",
  "age":29,
  "cars":"Ford"
}];
 var cars = [];
arr.forEach(function(car) {
    if (!cars.includes(car["cars"]) {
        cars.push(car["cars"]);
    }
})