JavaScript 数组操作

版权声明:本文为Martin原创文章,未经Martin允许不得转载。 https://blog.csdn.net/qq_36279445/article/details/88695660

最近项目用到了一些数组操作,整理记录一下

1.根据条件得到数组中符合条件的元素


            element.comments =
              element.comments.filter(({ status }) => status === CommentStatus.Active);

关键就是这个filter

2.判断是不是存在符合条件的元素,findIndex 获取到位置,后面Splice 就直接remove掉了


                const needRemoveIndex = element.comments.findIndex(f => f.id === comment.parentId);
                if (needRemoveIndex === -1) {
                  // deleted
                  element.comments.splice(needRemoveIndex, 1);
                }

3.合并数组


            element.comments = resultComment;
            result.push({ ...element, likedCount, savedCount, commentsCount });

关键是.pust, ...是ES6的拓展运算符

猜你喜欢

转载自blog.csdn.net/qq_36279445/article/details/88695660