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
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
-
Object.entries()
never returnsundefined
.forEach
always does. – Bergi Commented Feb 21, 2019 at 19:38 -
Are you positive you aren't required to perform a JSON operation on
queried_data
prior to interacting with it withObject
? – theaccordance Commented Feb 21, 2019 at 19:39 -
@theaccordance You are right, I can see something is not right from the console.log, after changing from
forEach
tomap
I am getting a messed up output. I need to see which JSON operation I will need to do. – calvert Commented Feb 21, 2019 at 19:44 - Try JSON.parse() – theaccordance Commented Feb 21, 2019 at 21:36
- I got it working already. Thank you – calvert Commented Feb 21, 2019 at 21:37
3 Answers
Reset to default 4forEach
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)
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);
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
!