gpt4 book ai didi

javascript - 如何从对象数组创建数组

转载 作者:行者123 更新时间:2023-11-28 15:04:40 25 4
gpt4 key购买 nike

鉴于以下情况:

var example = [{
"logged": {
"status": 0,
"status_name": "Logged",
"hours": 23 // to the hours array
},
"pending": {
"status": 3,
"status_name": "Pending",
"contribution": {
"hours": 0,
"count": 0
},
"verification": {
"hours": 6, // to the hours array
"count": 1
}
},
"denied": {
"status": 4,
"status_name": "Denied",
"contribution": {
"hours": 0,
"count": 0
},
"verification": {
"hours": 0, // to the hours array
"count": 0
}
},
"approved": {
"status": 2,
"status_name": "Approved",
"contribution": {
"hours": 4.5,
"count": 1
},
"verification": {
"hours": 0, // to the hours array
"count": 0
}
}
}];

我如何构造两 (2) 个数组,如下所示:

var statusNames = ["Logged", "Pending", "Denied", "Approved"];
var hours = [23, 6, 0, 0];

如果从解决方案中获取值,我可以推断如何获取其余部分。

最佳答案

您可以迭代数组和键,检查属性是否存在并将所需的部分包含到数组中。

var example = [{ "logged": { "status": 0, "status_name": "Logged", "hours": 23 }, "pending": { "status": 3, "status_name": "Pending", "contribution": { "hours": 0, "count": 0 }, "verification": { "hours": 6, "count": 1 } }, "denied": { "status": 4, "status_name": "Denied", "contribution": { "hours": 0, "count": 0 }, "verification": { "hours": 0, "count": 0 } }, "approved": { "status": 2, "status_name": "Approved", "contribution": { "hours": 4.5, "count": 1 }, "verification": { "hours": 0, "count": 0 } } }],
statusNames = [],
hours = [];

example.forEach(function (o) {
Object.keys(o).forEach(function (k) {
if ('hours' in o[k]) {
statusNames.push(k);
hours.push(o[k].hours);
return;
}
if ('verification' in o[k]) {
statusNames.push(k);
hours.push(o[k].verification.hours);
}
});
});
console.log(statusNames);
console.log(hours);

关于javascript - 如何从对象数组创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39599635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com