我从请求中获得响应,并且我想显示将数据操作为具有数组的对象。响应看起来像" events / month / event"。我想最终得到一个对象,其中每个月都是一个键,值是一个事件数组。我设法分开了关键和事件,但是当我想把它放到对象中时,我就缩短了。 我不知道响应中的键,因此我无法在resultObj中将它们定义为数组。出于这个原因,我不能使用push来扩展数组。
const response = [
"events/july/",
"events/july/summer-party",
"events/july/bbq",
"events/dec/",
"events/dec/christmas",
"events/dec/new-year"
];
let resultObj = {};
response.forEach(item => {
let str = item;
let key = str.replace("events/", "");
let event = key.split("/").pop();
key = key.substring(0, key.indexOf("/"));
resultObj[key] = [event];
})
console.log(resultObj);
// july: ["bbq"], dec: ["new-year"]
jsfiddle:https://jsfiddle.net/3z1de2r4/1/
答案 0 :(得分:3)
您可以拆分和解构键和值,只有在可用的值时才推送。
const response = ["events/july/", "events/july/summer-party", "events/july/bbq", "events/dec/", "events/dec/christmas", "events/dec/new-year"];
let resultObj = {};
response.forEach(item => {
let [, key, value] = item.split("/");
value && (resultObj[key] = resultObj[key] || []).push(value);
});
console.log(resultObj);

答案 1 :(得分:2)
一种可能的方法:
const response = [
"events/july/",
"events/july/summer-party",
"events/july/bbq",
"events/dec/",
"events/dec/christmas",
"events/dec/new-year"
];
let eventsByMonth = {};
response.forEach(item => {
let [, month, event] = item.split('/');
if (event === '') {
eventsByMonth[month] = [];
}
else {
eventsByMonth[month].push(event);
}
});
console.log(JSON.stringify(eventsByMonth));

这里的关键点是通过一次拆分操作提取整个数据集(为方便起见,使用ES6的解构赋值功能)。
顺便说一句,我不确定为什么你甚至需要这个只有一个月的时间?'你的回复中的行(例如' events / july /',' events / dec /'等等)。如果您能够删除它,您可以根据需要自动生成月份数组:if (!eventsByMonth.hasOwnProperty(month)) {
eventsByMonth[month] = [];
}
eventsByMonth[month].push(event);
...但现在不好,因为你需要检查一下“事件”'无论如何,空虚的字符串。