Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare objects within a array

I have an array

[{"name": "pay1","isEnabled": true},{"name": "pay2","isEnabled": false}]

I need to console the value where isEnabled is true.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried with forEach method but is not working if both value are true.

Because forEach iterates over each object so it will get one value at a time.

Below is my code

const arr = [{"name": "pay1","isEnabled": true},{"name": "pay2","isEnabled": true}]

arr.forEach(item => {

              if ((item.name === 'pay1' && item.isEnabled) && (item.name === 'pay2' && item.isEnabled)) {
                console.log('both enabled')
              } else if (item.name === 'pay1' && item.isEnabled) {
                console.log('pay1 enabled')
              } else if(item.name === 'pay2' && item.isEnabled){
             console.log('pay2 enabled')
              }
            })

How can i resolve this.

Thanks in advance……..

>Solution :

There is no need to run a loop.

Just find the elememnt with name having pay1 and name having pay1. Check the isEnabled of each node. If its true for both name, both are enabled or only one enabled.

const arr = [{ "name": "pay1", "isEnabled": true }, { "name": "pay2", "isEnabled": true }];
const item1 = arr.find(node => node.name === "pay1");
const item2 = arr.find(node => node.name === "pay2");
if (item1.isEnabled && item2.isEnabled) {
  console.log('both enabled')
} else if (item1.isEnabled) {
  console.log('pay1 enabled')
} else if (item2.isEnabled) {
  console.log('pay2 enabled')
} else {
  console.log('none enabled')
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading