我有一个基于这种结构的json数组:
[
{property1: "bmw", property2: value, property3: value, property4: value},
{property1: "mercedes", property2: value, property3: value, property4: value},
{property1: "bmw", property2: value, property3: value, property4: value},
{property1: "nissan", property2: value, property3: value, property4: value}
]
我如何过滤数组以查找第一次为property1
显示新值并将其存储在单独的数组中?
我希望数组如:["bmw", "mercedes", "nissan"]
答案 0 :(得分:1)
如果要存储唯一值,则应使用内置的JavaScript Set()
方法0
只会在.add(value)
尚未存在的情况下附加value
let carNames = new Set();
let cars= [
{ property1: "bmw" },
{ property1: "mercedes" },
{ property1: "bmw" },
{ property1: "nissan" }
];
cars.forEach(car => carNames.add(car.property1));
console.log(carNames.size);
for (let name of carNames) {
console.log(name);
}

答案 1 :(得分:0)
您可以创建一个数组carNames,遍历您的汽车,每次carNames数组中都不包含汽车的property1时,添加它
var cars= [
{property1: "bmw", property2: "d", property3: "", property4: "value"},
{property1: "mercedes", property2: "value", property3: "value", property4: "value"},
{property1: "bmw", property2: "value", property3: "value", property4: "value"},
{property1: "nissan", property2: "value", property3: "value", property4: "value"}
];
var carNames = [];
cars.forEach(function(car){
if (! carNames.includes(car.property1))
carNames.push(car.property1);
});
答案 2 :(得分:0)
鉴于原始数据的结构,我使用属性作为键将数组缩减为Map
var cars= [
{property1: "bmw", property2: "d", property3: "", property4: "value"},
{property1: "mercedes", property2: "value", property3: "value", property4: "value"},
{property1: "bmw", property2: "value", property3: "value", property4: "value"},
{property1: "nissan", property2: "value", property3: "value", property4: "value"}
];
var m = cars.reduce((map, entry) => {
if (!map.has(entry.property1)) {
map.set(entry.property1, entry)
}
return map
}, new Map())
console.log([...m.values()]);
console.log([...m.keys()]);

然后,您可以使用.values()
提取条目以获取完整对象,或.keys()
仅获取唯一品牌名称