javascript - JavaScript - 通过深度嵌套的对象键从标准数组中过滤对象?
问题描述
过去几天我一直在努力实现以下功能:
我有一个传入对象,其中包含一个嵌套子对象,它是一个日期列表。我想根据日期范围过滤原始对象,并返回修改后的过滤对象,只有指定的日期。
这是所需的功能:
let incomingObject = {
'one': {
id: "one",
dates: {
"2021-05-01": [{ a: "foo", b: "bar" }],
"2021-05-02": [{ a: "foo", b: "bar" }] } },
'two': {
id: "two",
dates: {
"2021-05-01": [{ a: "foo", b: "bar" }, { a: "foo2", b: "bar2" }],
"2021-05-02": [{ a: "baz", b: "far" }] } },
'three': {
id: "three",
dates: {
"2021-05-03": [{ a: "foo", b: "bar" }],
"2021-05-02": [{ a: "foo", b: "bar" }] } } };
// Function to get an array between two dates
const getDaysArray = function (s, e) {
for (var a = [], d = new Date(s); d <= new Date(e); d.setDate(d.getDate() + 1)) {
a.push(new Date(d));
}
let aStrings = a.map((date) => date.toISOString().slice(0, 10));
return aStrings;
};
我不知道如何实现这个函数,它将返回“过滤”对象:
filterResults(incomingObject, getDaysArray("2021-05-01", "2021-05-01"));
这是期望的结果 - 所有未通过过滤器的(子)对象都被排除在外:
let desiredResult = {
'one': {
id: "one",
dates: {
"2021-05-01": [{ a: "foo", b: "bar" }] } },
'two': {
id: "two",
dates: {
"2021-05-01": [{ a: "foo", b: "bar" }, { a: "foo2", b: "bar2" }] } } };
到目前为止我的进展:
let dateRange = getDaysArray("2021-05-01", "2021-05-01");
// This logs out only the required keys –– however, logging out the whole "parent" object is completely beyond my comprehension at the moment...
const filteredImages = Object.keys(images).forEach((key) => {
let imgObject = images[key];
Object.keys(images[key].dates).forEach((key) => {
if (dateRange.includes(key)) {
console.log(key);
}
});
});
非常感谢所有帮助或指示!
解决方案
const incomingObject={one:{id:"one",dates:{"2021-05-01":[{a:"foo",b:"bar"}],"2021-05-02":[{a:"foo",b:"bar"}]}},two:{id:"two",dates:{"2021-05-01":[{a:"foo",b:"bar"},{a:"foo2",b:"bar2"}],"2021-05-02":[{a:"baz",b:"far"}]}},three:{id:"three",dates:{"2021-05-03":[{a:"foo",b:"bar"}],"2021-05-02":[{a:"foo",b:"bar"}]}}};
const getDaysArray = function(e,t){for(var a=[],n=new Date(e);n<=new Date(t);n.setDate(n.getDate()+1))a.push(new Date(n));return a.map(e=>e.toISOString().slice(0,10))}
const filterResults = (data, days) => Object.entries(data).reduce((result, [k, v]) => {
const {dates, ...rest} = v
const filteredDates = days.reduce((acc, date) => {
if(v.dates[date]) acc[date] = v.dates[date]
return acc
}, {})
if (Object.keys(filteredDates).length)
result.push([k, { ...rest, dates: filteredDates }])
return result
}, [])
const res = filterResults(
incomingObject,
getDaysArray("2021-05-01", "2021-05-01")
)
console.log(Object.fromEntries(res))
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- reactjs - 如何在不弹出的情况下将 CopyWebpackPlugin 添加到 create-react-app?
- elf - 对于 ELF 文件,如何判断哪个部分包含执行二进制代码?
- jquery-select2 - Jquery Select2 多选与 Dragon NaturallySpeaking
- ios - 无法弄清楚为什么 Error 总是变成“nil”
- sql - 将两个表连接在一起时,无法理解哪个表是 count(*) 实际计数的。
- vba - 如何隐藏具有可变数据的行?
- python - 随机分割数据以用于此函数的训练和测试
- css - 垂直纵横比媒体查询
- node.js - 使用 root 用户的 NPM 安装权限被拒绝错误
- batch-file - 在文件名中查找日期并更改已过日期的名称