通过删除不需要的嵌套对象属性来过滤对象数组

时间:2018-05-28 12:19:25

标签: javascript arrays object filter

我有一个数组,其中包含工作日的对象,我希望按"打开"或者"关闭" (不要让我们在最后一个阵列中存在)。

let array = [
             [
               {"weekday":1,"opens":"09:00","closes":"11:00"}, 
               {"weekday":1,"opens":null,"closes":null}
             ],
             [
               {"weekday":2,"opens":"09:00","closes":"11:00"}, 
               {"weekday":2,"opens":"12:30","closes":"17:00"},
               {"weekday":2,"opens":"18:00","closes":"null"}
             ], ...
           ]

我想返回一个新创建的数组,以便我不会改变原始数组。

我目前的解决方案看起来很像但感觉很难看

let newArray = [];

array.forEach( (day, index)  => {
    day = day.filter( timeblock => 
       timeblock.opens != null && timeblock.closes != null
    );
    newArray.push(day);
});

如何过滤嵌套数组更优雅? (如果需要,jsfiddle:https://jsfiddle.net/2jukvsoy/1/

2 个答案:

答案 0 :(得分:1)

let newArray = array.map(day => 
    day.filter(timeblock => 
        timeblock.opens != null && timeblock.closes != null
    )
);

答案 1 :(得分:0)

没什么可做的,但也许你可以使用map而不是forEach

let array = [
             [
               {"weekday":1,"opens":"09:00","closes":"11:00"}, 
               {"weekday":1,"opens":null,"closes":null}
             ],
             [
               {"weekday":2,"opens":"09:00","closes":"11:00"}, 
               {"weekday":2,"opens":"12:30","closes":"17:00"},
               {"weekday":2,"opens":"18:00","closes":"null"}
             ]
           ]

const newArray = array.map(day => {
    return day.filter(timeblock => timeblock.opens && timeblock.closes);
});

console.log(newArray)