将 json 对象的值传递给另一个对象

时间:2021-01-16 03:23:09

标签: json react-native object fetch-api

我使用了 fetch API 从后端服务器获取数据。我从 fetch 函数返回了 JSON 对象数据,我想将对象中的每个值都传递给另一个对象。

function getvals() {

    return fetch('http://*********/users/timetable')
        .then(response => response.json())
        .then((responseData) => {
            console.log(responseData);
            return responseData;
        })

        .catch(error => console.log(error))

}

函数getvals()正在返回对象数据,这些数据看起来像这样:

[{"title": "Math","day": "FRI", "end_time": 11, "start_time": 9,location: "Classroom 403",extra_descriptions: "Chen"}]

现在我希望将对象数据的每个值都传递给这个对象:

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"],
    },
  
];

例如来自 getvals() 函数的 day 值我想将其传递到 startTime 对象中的 events_data

然后在视图中,events_data 将被传递给 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>

这样做的方法可能很简单,但我对这种方法很陌生,我找不到一种简单的方法来做到这一点。

1 个答案:

答案 0 :(得分:1)

您可以映射数据,然后将它们添加到数组 events_data 中。

函数 addData 将从提取请求接收的数据以所需格式推送到 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],
    });
  });
}

编辑:

如果你想渲染数据,那么你可以这样做:

const RenderData = () => {
  return (
    <View>
      {events_data &&
        events_data.result.map((data) => {
          return <Text>{data.title}</Text>;
        })}
    </View>
  );
};