【发布时间】:2020-01-09 03:14:16
【问题描述】:
我正在格式化我的数据,使其看起来像 results
当我使用 set var results = {} 时,结果会在渲染中输出,但是如果将 var results = [] 设置为数组,则它不会返回到渲染中。我可以在控制台日志中看到它,但在渲染中看不到。
这是一个可以玩的 CodeSandBox
https://codesandbox.io/s/blue-fire-x52qb
var results = {}
dates.forEach(function(item) {
var arrayOfEvents = [];
arrayOfObjects.forEach(function(value) {
if (item === value.info.startDate) {
// Found a match...
arrayOfEvents.push(value);
}
})
if (typeof results["d" + item.date] == "undefined") {
results["d" + item] = {
date: item,
events: arrayOfEvents
};
}
});
{JSON.stringify(results, null, 4)}
数组
var dates =
[
"01-06-2020",
"01-07-2020",
"01-08-2020",
"01-10-2020",
"02-04-2020"
]
对象数组
var arrayOfObjects =
[
{
"title": "Group President",
"id": "TpNY1SU_",
"info": {
"startDate": "01-06-2020"
}
},
{
"title": "TEST",
"id": "cEpPxopz",
"info": {
"startDate": "01-07-2020"
}
},
{
"title": "Example",
"id": "jnTMr_r7",
"info": {
"startDate": "01-07-2020"
}
},
]
设置results = [] 时获得[] 的期望(不工作结果)
results = [
"d01-06-2020": {
"date": "01-06-2020",
"events": [
{
"title": "Group President",
"id": "TpNY1SU_",
"info": {
"startDate": "01-06-2020"
}
}
]
},
"d01-07-2020": {
"date": "01-07-2020",
"events": [
{
"title": "TEST",
"id": "cEpPxopz",
"info": {
"startDate": "01-07-2020"
}
},
{
"title": "Example",
"id": "jnTMr_r7",
"info": {
"startDate": "01-07-2020"
}
}
]
},
]
设置results = {}时的工作结果
results = {
"d01-06-2020": {
"date": "01-06-2020",
"events": [
{
"title": "Group President",
"id": "TpNY1SU_",
"info": {
"startDate": "01-06-2020"
}
}
]
},
"d01-07-2020": {
"date": "01-07-2020",
"events": [
{
"title": "TEST",
"id": "cEpPxopz",
"info": {
"startDate": "01-07-2020"
}
},
{
"title": "Example",
"id": "jnTMr_r7",
"info": {
"startDate": "01-07-2020"
}
}
]
},
}
【问题讨论】:
-
信息太多了。请阅读minimal reproducible example,了解如何仅使用所需信息提出好的问题。
-
将数据减少到最低限度
-
@CharlieFish 我添加了一个代码沙箱,可以准确显示正在发生的事情
标签: javascript arrays reactjs object