我正在重新映射从一个完美运行的 API 接收到的 JSON 对象。问题不是插入单个数组 searchResultsReFormat
,而是在控制台中多次读取同一行但具有不同的值。
searchResultsReFormat: any = [];
this.searchResults.map(result => {
const customer = result.customer
const meals = result.meals
const newResults = [{
firstName : customer.firstName,
lastName : customer.lastName,
grade: this.gradeName,
meals: [meals]
}]
console.log(newResults)
this.searchResultsReFormat = newResults
})
但所有这些都应该被分组在一个数组searchResultsReFormat
中,当展开时,数据将会显示
最佳答案
map
实际上是根据提供的回调 转换每个值 来返回一个新数组。
你不需要插入或做事,你只需要:
- 将map的结果赋值给想要的值。
return
在回调中转换后的值。
//赋值在这里
this.searchResultsReFormat = this.searchResults.map(result => {
// ^--- callback here
const customer = result.customer;
const meals = result.meals;
const newResults = [{
firstName : customer.firstName,
lastName : customer.lastName,
grade: this.gradeName,
meals: [meals]
}];
return newResults; // <-- return here.
});
关于javascript - 重新映射 json 对象并将它们推送到一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57376982/