首页 > 解决方案 > 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);
        }
    });
});

非常感谢所有帮助或指示!

标签: javascriptarraysobject

解决方案


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; }


推荐阅读