设置 Object = [ ] 时返回"不渲染",在设置 Object = {} 时有效



>我正在格式化我的数据,使其看起来像results

当我使用 setvar results = {}时,结果是在渲染中输出,但是如果设置为数组var results = [],它不会返回到渲染中。我可以在控制台日志中看到它,但在渲染时看不到它。

这是一个代码沙盒可以玩

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

因为它是键值对数据,所以最好将数据保存在对象中并根据您的要求使用Object.valuesObject.keysObject.entries

这是使用 Es6flat()Object.values的解决方案

results = {
"d01-06-2020": {
"date": "01-06-2020",
"events": [
{
"title": "Group President",
"id": "TpNY1SU_",
"info": {
"startDate": "Mon Jan 06 2020 14:03:03 GMT-0500 (Eastern Standard Time)"
}
}
]
},
"d01-07-2020": {
"date": "01-07-2020",
"events": [
{
"title": "TEST",
"id": "cEpPxopz",
"info": {
"startDate": "Tue Jan 07 2020 11:16:52 GMT-0500 (Eastern Standard Time)"
}
},
{
"title": "Example",
"id": "jnTMr_r7",
"info": {
"startDate": "Tue Jan 07 2020 11:22:24 GMT-0500 (Eastern Standard Time)"
}
}
]
},
}
let res = Object.values(results).map(a=>a.events);
let dates = res.flat().map(a=>a.info.startDate);
console.log(dates)

最新更新