calvert
calvert

Reputation: 721

Object entries returning undefined

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

Upvotes: 1

Views: 7554

Answers (3)

Osama
Osama

Reputation: 3040

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);

Upvotes: 1

Bergi
Bergi

Reputation: 665020

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!

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281874

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)

Upvotes: 4

Related Questions