admin管理员组

文章数量:1405547

Look at my ments below the conversation with @Akrion who helped me fix this to see the solution!!!!

I'm really new to reactJS and axios both but was trying something with a classmate earlier and now I'm stuck. I want to render the "sport"-categories from the json-file, but the same categories shows up several times. What is a good practice to sort away the duplicates so that only e.g. "Football" shows up once?

Sorry, again, new to this. I've been trying some stuff like Javascript functions to sort it... but I'm just unsure where to put the code and I keep going in circles. Let me know if anything that I said is confusing (English is not my first language). Here is my code:

import React, { Component } from "react";
import axios from 'axios';

class SportsList extends Component {
  state = {
    posts: []
  }
  ponentDidMount(){
    axios.get('')
    .then(res => {
      this.setState({
        posts: res.data
      })
    })  
  }

  render() {
    console.log(this.props)
    const { posts } = this.state;
    const postList = posts.length ? (
        posts.map(post => {
          return (
            <div key={post.id}>
              <div>
                {post.sport}
              </div>
            </div>
          )
        })
      ) : (
        <div>No Sports Available</div>
      )
    return (
      <div> 
      {postList}
    </div>
    );
  }
}

export default SportsList;

Look at my ments below the conversation with @Akrion who helped me fix this to see the solution!!!!

I'm really new to reactJS and axios both but was trying something with a classmate earlier and now I'm stuck. I want to render the "sport"-categories from the json-file, but the same categories shows up several times. What is a good practice to sort away the duplicates so that only e.g. "Football" shows up once?

Sorry, again, new to this. I've been trying some stuff like Javascript functions to sort it... but I'm just unsure where to put the code and I keep going in circles. Let me know if anything that I said is confusing (English is not my first language). Here is my code:

import React, { Component } from "react";
import axios from 'axios';

class SportsList extends Component {
  state = {
    posts: []
  }
  ponentDidMount(){
    axios.get('https://json-file.json')
    .then(res => {
      this.setState({
        posts: res.data
      })
    })  
  }

  render() {
    console.log(this.props)
    const { posts } = this.state;
    const postList = posts.length ? (
        posts.map(post => {
          return (
            <div key={post.id}>
              <div>
                {post.sport}
              </div>
            </div>
          )
        })
      ) : (
        <div>No Sports Available</div>
      )
    return (
      <div> 
      {postList}
    </div>
    );
  }
}

export default SportsList;
Share Improve this question edited Dec 10, 2018 at 22:12 Joel 8 bitar asked Dec 4, 2018 at 21:01 Joel 8 bitarJoel 8 bitar 1231 gold badge3 silver badges17 bronze badges 1
  • Use Set rather than basic Array. developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Randy Casburn Commented Dec 4, 2018 at 21:02
Add a ment  | 

4 Answers 4

Reset to default 4

You should ideally fix the data on the server-side, but you can remove duplicates front-end also:

res.data.reduce((acc, post) => {
  const post1 = acc.find(x => x.sport === post.sport);
  if (!post1) {
    acc.push(post1);
  }
  return acc;
}, []);

Not the most efficient method, but it's simple

You can also simply group by your post id via Array.reduce and then get the values. Change your render to this:

render() {
    const { posts } = this.state;
    const uniquePosts = Object.values(posts.reduce((r,c) => { 
      r[c.id] = c 
      return r
    }, {}))
    const postList = uniquePosts.length ? (
        uniquePosts.map(post => {
          return (
            <div key={post.id}>
              <div>
                {post.sport}
              </div>
            </div>
          )
        })
      ) : (<div>No Sports Available</div>)
    return (<div>{postList}</div>);
  }
}

You can use reduce for filter sports before render, for example before setState

const sportsFiltered = sports.reduce((accum, sport) => {
    const accumulator = [...accum];
    if(!accumulator.some(item => item.id === sport.id)) {
        accumulator.push(sport);
    }
    return accumulator;
},[]);

class SportsList extends Component {
  state = {
    posts: []
  }
  ponentDidMount(){
    axios.get('https://json-file.json')
    .then(res => {
      this.setState({
        posts: sportsFiltered(res.data)
      })
    })  
  }

  render() {
    console.log(this.props)
    const { posts } = this.state;
    const postList = posts.length ? (
        posts.map(post => {
          return (
            <div key={post.id}>
              <div>
                {post.sport}
              </div>
            </div>
          )
        })
      ) : (
        <div>No Sports Available</div>
      )
    return (
      <div> 
      {postList}
    </div>
    );
  }
}
const newPosts = [...new Set(posts)]

本文标签: javascriptPrevent duplicates from json array with reactjs and axiosStack Overflow