0

I've created a simple filtering code that filters out 0s and nulls. Perhaps not the most elegant, but it works:

var data = [{"location": 30, "year": 2019},
            {"location": 60, "year" : 1928},
            {"location": 0, "year": 2019},
            {"location": 50, "year": 0}];
    
var filteredData = [];

for (var i = 0; i < data.length; ++i) {
  if (data[i].location !== null && data[i].location != 0) {
    filteredData.push({
      location: data[i].location,
      year: data[i].year
    })
  }
};
console.log(filteredData);

Now I would like to filter out 0s and nulls for other keys (e.g. year), how can I dynamically change key?

My (perhaps naive) thinking was to create a variable indicating the key I want to filter out

Unfortunately that didn't work. Does anyone have a suggestion or help me in the right direction?

var var1 = 'year';
    
var data = [{"location": 30, "year": 2019},
            {"location": 60, "year" : 1928},
            {"location": 0, "year": 2019},
            {"location": 50, "year": 0}];

var filteredData = [];

for (var i = 0; i < data.length; ++i) {
  if (data[i].var1 !== null && data[i].var1 != 0) {
    filteredData.push({
      location: data[i].location,
      year: data[i].year
    })
  }
};

console.log(filteredData)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Ant
  • 39
  • 5

3 Answers3

3

Your issue is that you need to use bracket notation instead of dot notation for variable keys.

That said, JavaScript has an Array filter method

You can then use every to have dynamic keys in an array:

const data = [{"location": 30, "year": 2019},
            {"location": 60, "year" : 1928},
            {"location": 0, "year": 2019},
            {"location": 50, "year": 0}];

const notZero = ["location","year"]

const filteredData = data.filter(item => notZero.every(key => item[key] !== 0))

console.log(filteredData)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
2

instead of data[i].var1 try data[i][var1]. the square brackets allows you to have a dynamic key.

gil
  • 2,388
  • 1
  • 21
  • 29
  • thanks, that was the answer I was looking for. So simple :) – Ant Jun 10 '22 at 12:33
  • [That was an easily found dupe](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – mplungjan Jun 10 '22 at 12:45
0

If you can have 0 or null in your data, you need to do this:

const data = [{"location": 30, "year": 2019},
            {"location": 60, "year" : 1928},
            {"location": 0, "year": 2019},
            {"location": 50, "year": 0}];

const filteredData = data.filter(item => !Object.values(item).filter(value => !value).length)

This lets you dynamically check all values within an object and check if all of them are truthy values, thereby catching all falsy values.

syedmh
  • 450
  • 2
  • 11