Home > Mobile >  How to filter json with key which have '0' as value?
How to filter json with key which have '0' as value?

Time:09-29

I have a JSON response with the key and the value, I want to filter only those whose weight is 1 Any help is greatly appreciated

{
"post": 1,
"bio": 1,
"hashtag": 0,
"profile": 0,
}

expected output

{
"post": 1,
"bio": 1
}

CodePudding user response:

let json = {
    "post": 1,
    "bio": 1,
    "hashtag": 0,
    "profile": 0,
}
const res = {}
for (const key in json) if (json[key] === 1) res[key] = json[key]

Essentially loops through each key of the json and checks if it's value is not zero. If the condition is true then it sets the res object value to the value of that property under the relevant key.

CodePudding user response:

You can filter over Object.entries.

const o = {
  "post": 1,
  "bio": 1,
  "hashtag": 0,
  "profile": 0,
};
let res = Object.fromEntries(Object.entries(o).filter(([k,v])=>v===1));
console.log(res);

  • Related