javascript - Applying filter in a nested array of objects using for each
问题描述
I'm trying to filter out the data points in an array of objects based on whether the particular property of the object is null. This array is however nested inside another array. See example below (i want to remove those objects from 'b' array which contain null in their 'c' property :
var data = [{
a: 1,
b: [{
c: null,
d: 10
}, {
c: 10,
d: 10
}]
}, {
a: 2,
b: [{
c: null,
d: 10
}, {
c: 10,
d: 10
}, {
c: 13,
d: 1
}]
}, {
a: 6,
b: [{
c: null,
d: 10
}, {
c: 10,
d: 10
}, {
c: null,
d: 10
}]
}]
data.forEach(function(d) {
d['b'].filter(function(da) {
return typeof(da['c']) == "number"
})
})
console.log(data)
The above code is not removing the "null" value objects from the nested array and returns the whole array as it is. What am i doing wrong here?
Update: I understood my mistake and i have updated the post with an answer. Thanks for all replies.
解决方案
data.forEach((dataPoint) => {
dataPoint.b = dataPoint.b.filter((dataChild) => {
return typeof dataChild.c === 'number'
})
})
您只需将“b”重新分配给新的过滤数组。
推荐阅读
- mysql - 基于mysql条目的shell脚本中的文件复制
- android - 升级 react-native 版本后出现错误
- html - 如何在css中为具有绝对位置的兄弟div元素的margin-left设置动态数字
- android-source - 构建 AOSP 扩展 ROM 时出现杰克错误
- react-native - React-Native:如何找到 ph://uri 的文件信息?
- python - 从 pandas DataFrame 中通过多个部分字符串匹配选择列
- php - 如何更改 getter 属性参数并显示不同的结果?
- sql - 为 SQL 中的重复记录分配相同的键以进行标识
- javascript - 检查特定宽度的屏幕尺寸变化
- javascript - 使用 fetch() 时 JS 脚本无法在 HTML 中运行