我怎样才能找到对象数据?

时间:2021-03-20 06:18:14

标签: javascript node.js reactjs react-native

我在FlatList的TodoItem组件中有多个对象值称为items。 另外,我有一个名为 itemtow

的对象值

我想要做的是将与项目对象的 id 值和 itemtow's CommentId 值匹配的项目对象值放入结果常量中。

这是我的数据和代码

商品数据

    item: {id: 163, content: "부모1", createdAt: "2021-03-19T16:23:20.000Z", updatedAt: "2021-03-19T16:23:20.000Z", UserId: 1, …}

    item: {id: 164, content: "부모2", createdAt: "2021-03-19T16:23:23.000Z", updatedAt: "2021-03-19T16:23:23.000Z", UserId: 1, …}

    item: {id: 165, content: "부모3", createdAt: "2021-03-19T16:23:38.000Z", updatedAt: "2021-03-19T16:23:38.000Z", UserId: 2, …}

    item: {id: 166, content: "부모4", createdAt: "2021-03-19T16:23:41.000Z", updatedAt: "2021-03-19T16:23:41.000Z", UserId: 2, …}

itemtow 数据

    itemtow: {id: 268,  CommentId: 166, content: "부모4", active: "1", createdAt: "2021-03-19T16:23:41.000Z", updatedAt: "2021-03-20T05:56:24.000Z", …}

预期的结果数据

    expected result =  {id: 166, content: "부모4", createdAt: "2021-03-19T16:23:41.000Z", updatedAt: "2021-03-19T16:23:41.000Z", UserId: 2, …}

这是我的代码

(todoList.js)

    const TodoList = ({item}) => {

      return (

        <>
        <FlatList
          data={singlePost?.Comments}
          keyExtractor={(item) => String(item.id)}
          
          ListEmptyComponent={<EmptyItem />}
          renderItem={({item}) => (
            <TodoItem
              item={item}
              itemtow={itemtow}
            />
          )}
        />
      </>
      );
    };

    export default TodoList;

(TodoItem.js)

    const TodoItem = ({item ,itemtow}) => {


      const result = item.filter((v) => v.id === itemtow.CommentId);

      console.log("result:",result);

      return (

      )

我该如何修复我的代码?我试过使用过滤器,但它不起作用。

2 个答案:

答案 0 :(得分:1)

TodoItem 组件中,item 是您传递给 FlatList 的数组 singlePost?.Comments 中的单个元素(对象)。

因此,您只需将 item.iditemRow.CommentId 对照:

const TodoItem = ({ item, itemRow }) => {

  const matched = item.id === itemRow.CommentId
  console.log('matched? ', matched, item)

  return <>...</>
}

此外,您可能希望将 [] 作为后备值传递给 FlatList

<FlatList
  data={singlePost?.Comments ?? []}
  ...

答案 1 :(得分:0)

实际上,filter 方法运行良好。

const items = [
  {id: 163, content: "부모1", createdAt: "2021-03-19T16:23:20.000Z", updatedAt: "2021-03-19T16:23:20.000Z", UserId: 1},
  {id: 164, content: "부모2", createdAt: "2021-03-19T16:23:23.000Z", updatedAt: "2021-03-19T16:23:23.000Z", UserId: 1},
  {id: 165, content: "부모3", createdAt: "2021-03-19T16:23:38.000Z", updatedAt: "2021-03-19T16:23:38.000Z", UserId: 2},
  {id: 166, content: "부모4", createdAt: "2021-03-19T16:23:41.000Z", updatedAt: "2021-03-19T16:23:41.000Z", UserId: 2}
];

const itemRow = {id: 268,  CommentId: 166, content: "부모4", active: "1", createdAt: "2021-03-19T16:23:41.000Z", updatedAt: "2021-03-20T05:56:24.000Z"};

const result = items.filter(v => v.id === itemRow.CommentId);
console.log(result);