英文:
How to created a nested array of objects using javascript Loop?
问题
我需要循环处理一个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);
但这不会给我所需的结果。
我该如何实现这个?
英文:
I need to loop an AJAX response and then create an array like this:
"2023-03-30": {"number": '', "url": ""},
"2023-03-30": {"number": '', "url": ""}
The loop looks like this:
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);
But this doesn't give me the required result.
How do I achieve this?
答案1
得分: 2
以下是翻译好的代码部分:
// 声明一个空对象来存储结果
var result = {};
// 遍历 AJAX 响应数组
for (i = 0; i < parsed_data.tasks.length; i++) {
// 从每个对象中提取日期、编号和 URL 值
var mydate = parsed_data.tasks[i].date;
var number = parsed_data.tasks[i].number;
var url = parsed_data.tasks[i].url;
// 检查结果对象中是否已存在具有该日期的对象
if (!result[mydate]) {
// 如果不存在,创建一个新对象,以日期作为键和一个空对象作为值
result[mydate] = {};
}
// 设置结果对象中相应对象的编号和 URL 值
result[mydate]["number"] = number;
result[mydate]["url"] = url;
}
// 输出最终结果
console.log(result);
英文:
You said you aren't getting the required response. What results are you actually getting? Maybe try something like this.
// 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);
答案2
得分: 0
If you need date you can use Object.keys
like:
const array = [
{"2023-03-30": {"number": '', "url": ''}},
{"2023-03-30": {"number": '', "url": ''}}
];
const result = array.map(el => Object.keys(el)).flat();
console.log(result);
英文:
If you need date you can use Object.keys
like:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const array = [
{"2023-03-30": {"number": '', "url": ""}},
{"2023-03-30": {"number": '', "url": ""}}
];
const result = array.map(el => Object.keys(el)).flat();
console.log(result);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论