我如何获得category_id列数据的唯一值 这是我的控制台日志数据
0: {category_id: "37", status: "4", category_name: "GO Thrones"}
1: {category_id: "41", status: "3", category_name: "need for speed"}
2: {category_id: "84", status: "4", category_name: "new"}
3: {category_id: "41", status: "3", category_name: "need for speed"}
4: {category_id: "37", status: "4", category_name: "GO Thrones"}
答案 0 :(得分:2)
使用 Object.keys(),我们可以使用 .reduce()返回所有唯一的ID值。
const data = {
0: {category_id: "37", status: "4", category_name: "GO Thrones"},
1: {category_id: "41", status: "3", category_name: "need for speed"},
2: {category_id: "84", status: "4", category_name: "new"},
3: {category_id: "41", status: "3", category_name: "need for speed"},
4: {category_id: "37", status: "4", category_name: "GO Thrones"}
}
const results = (data) =>
Object.keys(data).reduce((result, key) => {
(!~result.indexOf(data[key].category_id)) &&
result.push(data[key].category_id);
return result
}, [])
console.log(results(data)); // [ '37', '41', '84' ]
为了方便起见,这里将其重构为一个衬里,尽管显然不易理解。
const results = (d) => Object.values(d).reduce((r, i) => !~r.indexOf(i.category_id) ? (r.push(i.category_id), r) : r , []);
console.log(results(data)); // [ '37', '41', '84' ]