提问人:drago 提问时间:3/7/2023 最后编辑:drago 更新时间:3/7/2023 访问量:52
如何使用javascript Loop创建嵌套的对象数组?[关闭]
How to created a nested array of objects using javascript Loop? [closed]
问:
我需要循环一个AJAX响应,然后创建一个像这样的数组:
"2023-03-30": {"number": '', "url": ""},
"2023-03-30": {"number": '', "url": ""}
循环如下所示:
var columns = {};
for (var i=0; i < parsed_data.tasks.length; i++) {
var mydate = parsed_data.tasks[i].date;
columns.push(mydate);
}
console.log(columns);
但这并不能给我所需的结果。
如何实现此目的?
答:
0赞
Simone Rossaini
3/7/2023
#1
如果你需要日期,你可以这样使用:Object.keys
const array = [
{"2023-03-30": {"number": '', "url": ""}},
{"2023-03-30": {"number": '', "url": ""}}
];
const result = array.map(el => Object.keys(el)).flat();
console.log(result);
2赞
anomie87
3/7/2023
#2
你说你没有得到所需的回复。你实际得到了什么结果?也许可以尝试这样的事情。
// Declare an empty object to store the result
var result = {};
// Loop through the AJAX response array
for (i = 0; i < parsed_data.tasks.length; i++) {
// Extract the date, number, and url values from each object
var mydate = parsed_data.tasks[i].date;
var number = parsed_data.tasks[i].number;
var url = parsed_data.tasks[i].url;
// Check if an object with the date already exists in the result object
if (!result[mydate]) {
// If it doesn't exist, create a new object with the date as the key and an empty object as the value
result[mydate] = {};
}
// Set the number and url values for the corresponding object in the result object
result[mydate]["number"] = number;
result[mydate]["url"] = url;
}
// Output the final result
console.log(result);
评论