GrayHat
GrayHat

Reputation: 149

What is the better way to check in array of nested object

I'd like to check at least one checked field is true and not disabled:

const test = 
  [ { Title: 
      { Article: { checked: true,  disabled: true  } 
      , Desc:    { checked: false, disabled: false } 
    } } 
  , { News: 
      { Dashboard: { checked: false, disabled: false} 
    } }
  ] 

I tried like this:

const checkedItems = () => {
  let value = false;
  test.forEach(el => Object.entries(el).forEach(([title, checkboxProps]) => {
    Object.entries(checkboxProps).forEach(([name, config]) => {
      if (config["checked"] && !config["disabled"]) {
        value = true
      }
    })
  }))
  return value;
};

Upvotes: 1

Views: 54

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370989

A couple of flatMaps with Object.values can do it pretty cleanly.

const test = [{
  Title: {
    Article: {
      checked: true,
      disabled: true
    },
    Desc: {
      checked: false,
      disabled: false
    }
  }
}, {
  News: {
    Dashboard: {
      checked: false,
      disabled: false
    }
  }
}];

const atLeastOneCheckedAndNotDisabled = test
  .flatMap(Object.values)
  .flatMap(Object.values) // now we have an array of [{checked, disabled}]
  .some(innerObj => innerObj.checked && !innerObj.disabled);
  
console.log(atLeastOneCheckedAndNotDisabled);

You don't care about the keys, only the values, so Object.values will make things easier to work with than Object.entries.

Upvotes: 4

Related Questions