简体   繁体   English

如何按日期过滤嵌套的对象数组

[英]How filter nested array of objects by date

I have an array like this:我有一个这样的数组:

const data =  [
  {
    id: '3499934913',
    user_data: {
      user_data_stays: [
        {
          value: '30.0',
          date: '2021-10-01T12:55:00.000Z',
        },
        {
          value: '30.0',
          date: '2021-11-01T12:55:00.000Z',
        },
        {
          value: '30.0',
          date: '2021-13-01T12:55:00.000Z',
        }
      ],
    }
  },
  {
    id: '43534535',
    user_data: {
      user_data_stays: [
        {
          value: '30.0',
          date: '2021-11-01T12:55:00.000Z',
        },
        {
          value: '30.0',
          date: '2021-12-01T12:55:00.000Z',
        },
        {
          value: '30.0',
          date: '2021-13-01T12:55:00.000Z',
        }
      ],
    }
  },
]

How can I keep the structure of the whole array but filter in user_data_stays only those objects which date is equal to 2021-10-01T12:55:00.000Z ?如何保留整个数组的结构,但仅在user_data_stays中过滤那些日期等于2021-10-01T12:55:00.000Z的对象?

I tried using filter and some but I am not able to get to the nested element inside.我尝试使用过滤器和一些但我无法进入内部的嵌套元素。 I think the problem is the amount of nesting, and I can't deal with that.我认为问题是嵌套的数量,我无法处理。 I would appreciate your help.我将不胜感激你的帮助。

You could use forEach on the outer array and run filter method on inner array with the help of de-structuring, the object reference will update the outer object in-place.您可以在外部数组上使用 forEach 并在解构的帮助下对内部数组运行 filter 方法,object 引用将就地更新外部 object。

 const data = [ { id: "3499934913", user_data: { user_data_stays: [ { value: "30.0", date: "2021-10-01T12:55:00.000Z" }, { value: "30.0", date: "2021-11-01T12:55:00.000Z" }, { value: "30.0", date: "2021-13-01T12:55:00.000Z" }, ], }, }, { id: "43534535", user_data: { user_data_stays: [ { value: "30.0", date: "2021-11-01T12:55:00.000Z" }, { value: "30.0", date: "2021-12-01T12:55:00.000Z" }, { value: "30.0", date: "2021-13-01T12:55:00.000Z" }, ], }, }, ]; data.forEach(({ user_data }) => { user_data.user_data_stays = user_data.user_data_stays.filter(({ date }) => date === '2021-10-01T12:55:00.000Z'); }); console.log(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM