简体   繁体   English

如何从对象数组中过滤具有相同标题的数据?

[英]How do I filter data with the same title from an array of objects?

I have been trying to put up with the following behaviour for pending checks:我一直在尝试忍受以下待处理检查的行为: 在此处输入图像描述

Instead I have been only able to do as follows:相反,我只能做到以下几点: 在此处输入图像描述

My data looks like follow:我的数据如下所示: 在此处输入图像描述

在此处输入图像描述

The code that I have written uptil now is as follows:我写到现在的代码如下:

import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  ActivityIndicator,
  StyleSheet,
  SafeAreaView,
  TouchableOpacity,
  Image,
  FlatList,
} from 'react-native';
import axios from 'axios';
import {ROOT} from '../../services/ApiUrl';
import {vc} from '../../api';
import {timestamp} from '../../utils/dateUtils';
import {Images} from '../../assets/index';
export default function NutritionAssessment(props) {
  const {navigation} = props;
  const [index, setIndex] = useState(0);
  const [pendingIndex, setPendingIndex] = useState(null);
  const [questionsData, setQuestionsData] = useState({});
  const [idd, setIdd] = useState(null);
  const [optionid, setOptionId] = useState([]);
  const [group, setGroup] = useState(null);
  // console.log(props.route.params?.id);
  const id = props.route.params?.id;
  // console.log('id', id);
  // const getQuestions = async () => {
  //   const response = await API.get(
  //     `/wellchild/nutri-check?screen_type=116&child_id=${id}&vc=${vc}`,
  //   );
  //   console.log('nutrition response', response.data.content);
  //   setQuestionsData(response.data.content);
  //   setPendingIndex(questionsData.questions.length - 1);
  // };
  const getQuestions = () => {
    axios
      .get(
        `${ROOT}/wellchild/nutri-check?screen_type=116&child_id=${id}&vc=${vc}`,
      )
      .then(function (response) {
        console.log('nutrition response', response.data.content);
        setQuestionsData(response.data.content);
        setPendingIndex(response.data.content.questions.length - 1);
      })
      .catch(function (error) {
        console.log(error);
      });
  };
  useEffect(() => {
    getQuestions();
  }, []);

  const post = (item) => {
    console.log('ITEM', item);
    let chosen_option_id = optionid.concat(item.id);
    setOptionId(chosen_option_id);
    axios
      .post(`${ROOT}/wellchild/nutri-check/answer?screen_type=116&vc=55`, {
        answer_type: item.type,
        assessment_age: questionsData.assessment_age,
        child_id: id,
        chosen_option_id: optionid,
        event_date: timestamp,
        question_id: item.id,
        score: item.score,
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  };
  const renderItem = ({item}) => {
   
    return (
      <View>
        <TouchableOpacity
          style={Styles.options}
          onPress={() => SelectOption(item)}>
          <Text style={Styles.optionText}>{item.name}</Text>
        </TouchableOpacity>
      </View>
    );
  };
  const SelectOption = (item) => {
    console.log('selected', item);
    console.log('set ID', idd);
    if (index === questionsData.questions.length - 1) {
      navigation.navigate('nutritionassessmentreport', {
        id: id,
        assessment_age: questionsData.assessment_age,
      });
    } else {
      setIndex(index + 1);
      setPendingIndex(pendingIndex - 1);
    }
    post(item);
    console.log('incremented index', index);
    console.log('decreased index', pendingIndex);
    // console.log('length',questionsData.questions.length)
  };

  return (
    <SafeAreaView
      style={{
        flex: 1,
        alignItems: 'center',
        padding: 16,
      }}>
      {questionsData &&
      questionsData != {} &&
      questionsData != null &&
      questionsData != '' &&
      questionsData != undefined
        ? questionsData.questions &&
          questionsData.questions != '' &&
          questionsData.questions != undefined &&
          questionsData.questions != null &&
          questionsData.questions.length > 0 && (
            <View style={{alignItems: 'center', height: '100%', padding: 10}}>
              <Text style={Styles.title}>
                {questionsData.questions[index].title}
              </Text>
              <Text style={Styles.text}>
                {questionsData.questions[index].text}
              </Text>
              <FlatList
                renderItem={renderItem}
                data={questionsData.questions[index].options}
              />

              {pendingIndex != null && pendingIndex != undefined && (
                <View style={{marginTop: 100, alignItems: 'center'}}>
                  <View style={{flexDirection: 'row'}}>
                    <Text style={Styles.pendingIndex}>{pendingIndex}</Text>
                    <Text style={{marginLeft: 7, fontSize: 12}}>
                      Pending Checks
                    </Text>
                  </View>
                  <Image
                    source={Images.pendingchecks}
                    style={{width: 60, height: 60, marginTop: 17}}
                  />
                </View>
              )}

              {console.log('decreased index.....', pendingIndex)}
            </View>
          )
        : null}
    </SafeAreaView>
  );
}
const Styles = StyleSheet.create({
  title: {
    fontWeight: 'bold',
    fontSize: 16,
    color: '#000',
  },
  text: {
    fontSize: 16,
    marginTop: 21,
    marginBottom: 30,
    fontWeight: '600',
  },
  options: {
    borderRadius: 40,
    height: 40,
    padding: 25,
    width: 300,
    alignItems: 'center',
    borderColor: '#000',

    borderWidth: 0.8,
    justifyContent: 'center',
    marginBottom: 20,
  },

  pendingIndex: {
    fontSize: 12,
    color: '#D32F2F',
    fontWeight: 'bold',
  },
  optionText: {
    fontSize: 14,
    color: '#000',
    textAlign: 'center',
  },
  optionSelectedText: {
    fontSize: 14,
    color: '#fff',
  },
});

Am really stuck with how to implement the expected behaviour which is with every same title in the array of objects->that would be grouped together and the answers selected for that particular group would be decremented one by one from the group.length then it moves to the next group.我真的很坚持如何实现对象数组中每个相同标题的预期行为->将被分组在一起,并且为该特定组选择的答案将从 group.length 中逐个递减,然后它会移动到下一组。

I hope am able to make myself clear, any help would be great我希望能够让自己清楚,任何帮助都会很棒

You can do something like你可以做类似的事情

const groupedBytitle = {};

questions.forEach(question => {
  groupedBytitle.hasOwnProperty(question.title)
    ? groupedBytitle[question.title].push(question)
    : (groupedBytitle[question.title] = [question]);
});

This will group your questions by title这将按标题对您的问题进行分组

{
title : [question, question],
title2: [question],
title3: [question, question, question]
}

to get number of questions for selected group.获取所选组的问题数。

const totalQuestions = questionsData.filter(item => item.group === selectedGroup).length;

this will give you the number of questions for the selected group.这将为您提供所选组的问题数量。 where selectedGroup should be the selected group key value (allergies).其中 selectedGroup 应该是选定的组键值(过敏)。

Now you need to know how many question you have answered.现在你需要知道你回答了多少问题。

const numberOfQuestionsRemaining = totalQuestions.filter(item => item.isAnswer != true).length;

totalQuestions will be array of questions for the selected group. totalQuestions 将是所选组的问题数组。 you have filtered the array and get the number of questions which are not answered yet.您已经过滤了数组并获得了尚未回答的问题数量。

you need to do one thing.你需要做一件事。 After you answer any single question, you need to add a key in your question object.回答任何一个问题后,您需要在问题 object 中添加一个键。 > isAnswer = true; > isAnswer = 真; it will keep that the question has been answer.它将保持问题已得到回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM