Home > Net >  Change object to array and use map function in react native
Change object to array and use map function in react native

Time:06-09

I get list response from django server. This is what responseJson.bill looks like

[
  {"ch": 0, "day": 9, "de": 0, "dr": 0, "en": 0, "etc": 1600, "id": 111, "ja": 0, "joy": 0, "ko": 0, "location": "경기 부", "month": 6, "mt": 0, "name": "삼계", "price": 1600, "shop": 0, "user_id_id": 2, "year": 2022},
  {"ch": 0, "day": 9, "de": 0, "dr": 0, "en": 0, "etc": 17, "id": 112, "ja": 0, "joy": 0, "ko": 0, "location": "경기 부개", "month": 6, "mt": 0, "name": "chicken", "price": 17, "shop": 0, "user_id_id": 2, "year": 2022}, 
  {"ch": 0, "day": 9, "de": 0, "dr": 0, "en": 0, "etc": 0, "id": 113, "ja": 0, "joy": 0, "ko": 18, "location": "경기 부개", "month": 6, "mt": 0, "name": "galbi", "price": 18, "shop": 0, "user_id_id": 2, "year": 2022}
];

In react native, type of "bill" is object now and I want to change to array and use map function to show those lists at screen

I want to etract just "name" and "price" properties from list and show at the screen What should I do?

I tried to use map function but error says "can't use map function in object"

Here's my code

import React, {useState, Component} from 'react';
import {Alert, View, Text, SafeAreaView, TextInput, StyleSheet, Image, Pressable, Dimensions, TouchableOpacity} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Modal from 'react-native-modal';
import {Calendar} from 'react-native-calendars'
import {
  LineChart,
  ProgressChart,
  ContributionGraph,
} from "react-native-chart-kit";


 const LedgerScreen = () => {
  const [bill, setBill] = useState(false);
  const [datebill, setDateBill] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);

  const get_today = async() => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth()   1;
    const day = now.getDate();

    const userData = await AsyncStorage.getItem('userData');
    const profile = JSON.parse(userData);

    fetch('http://13.209.105.69:8001/user/date/', {
    //fetch('http://localhost:8000/user/date/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: "Token "   profile.token,
      },
      body: JSON.stringify({
        year: year,
        month: month,
        day: day,
      })
    })
    .then((response) => response.json())
    .then((responseJson) => {
        console.log(responseJson);
        if(responseJson.status === 'success') {
              setBill(JSON.stringify(responseJson.list));
              //alert(bill);
        } else {
            alert("fail");
        }
    })
    .catch((error) => {
        console.error(error);
    });
  }

  const get_calendar_day = async(Date) => {
      const year = Date.year
      const month = Date.month
      const day = Date.day

      const userData = await AsyncStorage.getItem('userData');
      const profile = JSON.parse(userData);

      fetch('http://13.209.105.69:8001/user/date/', {
      //fetch('http://localhost:8000/user/date/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: "Token "   profile.token,
        },
        body: JSON.stringify({
          year: year,
          month: month,
          day: day,
        })
      })
      .then((response) => response.json())
      .then((responseJson) => {
          console.log(responseJson);
          if(responseJson.status === 'success') {
              setDateBill(JSON.stringify(responseJson.list));
          } else {
              alert("fail");
          }
      })
      .catch((error) => {
          console.error(error);
      });
  }

  return (
  <View>
    <Modal
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
            setModalVisible(!modalVisible);
        }}
    >
      <View style={styles.modalView}>
        <Calendar
            onDayPress={day => {
                get_calendar_day(day)
            }}
            style={styles.calendar}
            hideExtraDays={true}
        />
        <Pressable
            onPress={() => setModalVisible(!modalVisible)}
        >
            <Text style={styles.textStyle}>접기</Text>
        </Pressable>
      </View>
    </Modal>
    <View style={styles.view}>
      <Pressable
          onPress={() => setModalVisible(true)}
      >
          <Image
            source={require('../../Image/calendar.png')}
            style={styles.ImageIconStyle}
          />
      </Pressable>
      <TouchableOpacity
          onPress={() => get_today()}
      >
        <Text>오늘의 소비</Text>
      </TouchableOpacity>
    </View>
    <Text>
      {bill}
    </Text>
  </View>
  );
};

export default LedgerScreen;

const styles = StyleSheet.create({
  calendar: {
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
   modalView: {
      margin: 20,
      backgroundColor: "white",
      borderRadius: 20,
      padding: 35,
      alignItems: "center",
      shadowColor: "#000",
      shadowOffset: {
        width: 0,
        height: 2
      },
      shadowOpacity: 0.25,
      shadowRadius: 4,
      elevation: 5
   },
   textStyle: {
      color: "black",
      textAlign: "center"
   },
   ImageIconStyle: {
        padding: 10,
        margin: 10,
        height: 25,
        width: 25,
   },
   view: {
     padding: 10,
     margin: 45,
     flexDirection: 'row',
     justifyContent: 'center',
     alignItems: 'center',
   }
});

I tried to use map function in here

<Text>
      {bill}
</Text>

CodePudding user response:

From the data you showed as the response from the server, the type by default is Array (an array of objects) but you are converting it to test using JSON.stringify. Instead of converting that to string, store the response directly as

setBill(responseJson.list);

It will now store an array in bill (if responseJson.list is an array).

After that, you can directly use map function instead of your <Text>{bill}</Text>

{bill.map((x, i) => {
    return <Text>{x.name} {x.price}</Text>
})}

Again it depends on the data being received from the server. If responseJson.list is array by default, setBill will have an array

CodePudding user response:

No need to convert inner objects into an array. You can loop over the main array and then get the inner object properties via using map.

Demo :

class LoopThrough extends React.Component {
  render() {
    return (
      <div>
        {this.props.bills.map(bill => (
          <li key={bill.id}>Name: <b>{bill.name}</b>, Price: <b>{bill.price}</b></li>
        ))}
      </div>
    );
  }
}

ReactDOM.render(
  <LoopThrough bills={[
  {"ch": 0, "day": 9, "de": 0, "dr": 0, "en": 0, "etc": 1600, "id": 111, "ja": 0, "joy": 0, "ko": 0, "location": "경기 부", "month": 6, "mt": 0, "name": "삼계", "price": 1600, "shop": 0, "user_id_id": 2, "year": 2022},
  {"ch": 0, "day": 9, "de": 0, "dr": 0, "en": 0, "etc": 17, "id": 112, "ja": 0, "joy": 0, "ko": 0, "location": "경기 부개", "month": 6, "mt": 0, "name": "chicken", "price": 17, "shop": 0, "user_id_id": 2, "year": 2022}, 
  {"ch": 0, "day": 9, "de": 0, "dr": 0, "en": 0, "etc": 0, "id": 113, "ja": 0, "joy": 0, "ko": 18, "location": "경기 부개", "month": 6, "mt": 0, "name": "galbi", "price": 18, "shop": 0, "user_id_id": 2, "year": 2022}
]} />,
  document.getElementById('container')
);
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="container">
</div>

  • Related