首页 > 解决方案 > 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.

标签: javascript

解决方案


data.forEach((dataPoint) => {
  dataPoint.b = dataPoint.b.filter((dataChild) => {
    return typeof dataChild.c === 'number'
  })
})

您只需将“b”重新分配给新的过滤数组。


推荐阅读