Home > Back-end >  Make a button for True items in an Object (from API res)
Make a button for True items in an Object (from API res)

Time:11-14

I'm doing a GET fetch request to my DB on page load and wish to display only the True items.

The response json object has 32 items returned from the API. They are all key value pairs (with boolean values) eg:

{
Apple: false
Banana: false
Orange: true
Kiwi: true
}

I need to find ONLY the true items, create a button element for each true item, set the button text label from the Key, and add this to my page inside an empty div.

I've played with If/Else and turning the Object into an Array with Object.entries - but I'm out of my depth and don't really know the right approach.

Any help appreciated. Cheers

(Vanilla JS only thx)

CodePudding user response:

In javascript, you can use Object.entries() to iterate an Object and get their Keys and Values.

const obj = {
  Apple: false,
  Banana: false,
  Orange: true,
  Kiwi: true
 }

const results = [];

for (const [fruit,boolean] of Object.entries(obj)) {
  if (boolean) results.push(fruit);
}

console.log(`There are ${results.length} 'true' in the given obj.\nThey are:\n${results.join(',\n')}`)

// output:
// There are 2 'true' in the given obj.
// They are:
// Orange,
// Kiwi

CodePudding user response:

You can make use of array method array.filter() to filter the true values.

Then select the empty div like, document.getElementById('container') and iterate the filtered data and create the button element using document.createEelement and then add text from key and append the button to the container div.

const obj = {
Apple: false,
Banana: false,
Orange: true,
Kiwi: true,
};

const data = Object.entries(obj).filter(([key, value]) => value);

const container = document.getElementById('container');

data.forEach(item => {
  const button = document.createElement('button');
  button.innerText = item[0];
  container.append(button);
});
#container button {
  margin: 10px;
}
<div id="container"> </div>

  • Related