如何比较和过滤2个对象数组

时间:2020-01-16 09:14:48

标签: reactjs typescript

你好,我正在用Typescript在React中做一个应用程序,比较两个状态(基本上是2个对象数组并进行过滤时遇到问题,所以我只取回allBooks数组中包含的那些状态) ,这是接口:

export interface IBook {
  book_id: number;
  book_name: string;
  release_year: number;
}

然后我上课的状态:

class Home extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);

    this.state = {
      users: [],
      userBooks: [],
      allBooks: []
    };
  }

然后是比较功能:

 filterBooks = () => {
    const { allBooks, userBooks } = this.state;
    let notUserBooks = allBooks.filter(
      ({ book_id }: { book_id: number }) => !userBooks.includes({book_id}));
    console.log(notUserBooks, allBooks);
  };`

我不知道我在做什么错,但是console.log在notUserBooks中得到的结果与在allBooks中得到的结果相同,我的意思是allBooks中包含3个项目,并且在过滤器后的控制台日志中,我得到了全部3个项目。...这是控制台输出:

(3) [{…}, {…}, {…}]
0: {book_name: "the lord of the rings", release_year: 1950}
1: {book_name: "the butterfly", release_year: 1980}
2: {book_name: "the hobbit", release_year: 1960}
length: 3
__proto__: Array(0) 
(3) [{…}, {…}, {…}]
0: {book_name: "the lord of the rings", release_year: 1950}
1: {book_name: "the butterfly", release_year: 1980}
2: {book_name: "the hobbit", release_year: 1960}
length: 3
__proto__: Array(0)```

3 个答案:

答案 0 :(得分:1)

尝试更改此内容:

 filterBooks = () => {
    const { allBooks, userBooks } = this.state;
    let notUserBooks = allBooks.filter(
      ({ book_id }: { book_id: number }) => !userBooks.includes({book_id}));
    console.log(notUserBooks);
  };

对此:

 filterBooks = () => {
    const { allBooks, userBooks } = this.state;
    let notUserBooks = allBooks.filter(
      ({ book_id }: { book_id: number }) => !userBooks.map(book => book.book_id).includes(book_id));
    console.log(notUserBooks);
  };

通常,您无法在javascript中比较对象。一个简单的测试:

const a = { test: 'test' };
const b = { test: 'test' };
alert(a === b);

答案 1 :(得分:0)

您可以使用Array.some()来检查userBooks是否包含图书项目:

let notUserBooks = allBooks.filter((book) => !userBooks.some((userBook) => userBook.book_id === book.book_id));

console.log(notUserBooks);

答案 2 :(得分:0)

对象是引用类型,因此您不能仅使用===或==比较对象。 过滤方法的一种解决方案是(分为2种方法):

const bookIds = (books: IBook[]): number[] => !!books && books.map(({bookId})=> bookId);

const filterBooks = (userBooks: IBook[], allBooks: IBook[]): IBook[] => 
  !!allBooks && allBooks.filter(({bookId}) => bookIds(userBooks).indexOf(bookId) === -1 );

In this project you can see it better(带有Typescript和React)