Reputation: 101
I used a fetch API to get data from backend server. I returned JSON object data from fetch function and I want to pass every single value in the object to another object.
function getvals() {
return fetch('http://*********/users/timetable')
.then(response => response.json())
.then((responseData) => {
console.log(responseData);
return responseData;
})
.catch(error => console.log(error))
}
the function getvals()
is returning the object data, these data looks like this:
[{"title": "Math","day": "FRI", "end_time": 11, "start_time": 9,location: "Classroom 403",extra_descriptions: "Chen"}]
now I want every single value of the object data to be passed to this object:
const events_data = [
{
title: "Math",
startTime: genTimeBlock("WED", 9),
endTime: genTimeBlock("WED", 10),
location: "Classroom 403",
extra_descriptions: ["Kim", "Lee"],
},
{
title: "Mandarin",
startTime: genTimeBlock("TUE", 9),
endTime: genTimeBlock("TUE", 10),
location: "Language Center",
extra_descriptions: ["Chen"],
},
{
title: "Japanese",
startTime: genTimeBlock("FRI", 9),
endTime: genTimeBlock("FRI", 10),
location: "Language Center",
extra_descriptions: ["Nakamura"],
},
];
for example the value of day from getvals()
function i want to pass it to be set in in startTime
in events_data
object
then within the the view the events_data
will be passed to events props
:
<SafeAreaView style={{ flex: 1, padding: 30 }}>
<View style={styles.container}>
<TimeTableView
scrollViewRef={this.scrollViewRef}
**events={// events.data will be passed here as object format //}**
pivotTime={8}
pivotDate={this.pivotDate}
numberOfDays={this.numOfDays}
onEventPress={getvals}
headerStyle={styles.headerStyle}
formatDateHeader="dddd"
locale="en"
/>
</View>
</SafeAreaView>
it may the way to do this is easy but im new with this approche and i couldn't find an easy way to do it.
Upvotes: 1
Views: 1032
Reputation: 6819
You can map over the data and then add them to the array events_data
.
The function addData
pushes the data received from the fetch request in the desired format to the events_data
.
function getvals() {
fetch("http://*********/users/timetable")
.then((response) => response.json())
.then((output) => {
addData(output, events_data);
})
.catch((error) => console.log(error));
}
function addData(data, data2) {
data.forEach(d) => {
data2.push({
title: d.title,
startTime: genTimeBlock(d.day, d.startTime),
endTime: genTimeBlock(d.day, d.endTime),
location: d.location,
extra_description: [d.extra_description],
});
});
}
Edit:
If you wanted to render the data then you can do it like this:
const RenderData = () => {
return (
<View>
{events_data &&
events_data.result.map((data) => {
return <Text>{data.title}</Text>;
})}
</View>
);
};
Upvotes: 1