1

I have a json object returned from a SQL query. I want to filter out the json key before sending back to the front end. If the key is true, return back to the front end is what I am looking for.

In my server file I have this line.

          let returned_data = Object.entries(queried_data[0]).forEach((key, value) => {
            return value === true ? key : null
          })
          res.json(returned_data)

This is an example of my returned json after SQL querying.

[{first_name: 'testing', has_apple: true, has_pear: true, has_beans: false}]

I am expecting the returned_data to have ['has_apple', 'has_pear']. Right now I am getting undefined for returned_data

calvert
  • 631
  • 10
  • 33

3 Answers3

4

forEach doesn't return anything map does. Also Object.entries returns an array of arrays and hence you need to destructure the value in map function to get key and value. Change your code to

      let returned_data = Object.entries(queried_data[0]).map(([key, value]) => {
        return value === true ? key : null
      })
      res.json(returned_data)
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1

As other answers say forEach() doesn’t return anything so either you have to use map() or create an array and push value to it if true

var new_data=[];
Object.entries(queried_data[0]).forEach((key, value) => {
       if( value===true){new_data.push(key)}
});
console.log(new_data);
Osama
  • 2,912
  • 1
  • 12
  • 15
  • 1
    This gives exactly what I wanted for the result. I will try out others' solutions too for knowledge. Thank you. – calvert Feb 21 '19 at 19:54
0

I think you are looking for

const returned_data = Object.entries(queried_data[0]).map((key, value) => {
    return value === true ? key : null
}).filter(key => {
    return key !== null
});

or simply

const returned_data = Object.keys(queried_data[0]).filter(key, queried_data[0][key] === true);

Don't use forEach!

Bergi
  • 630,263
  • 148
  • 957
  • 1,375