如何在React JS中映射和过滤重复值

时间:2019-01-27 08:50:06

标签: javascript reactjs

我如何获得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"}

1 个答案:

答案 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' ]​​​​​