skip to Main Content
Array = {
  0 : { NAME: 'A' , PET :'DOG' , AGE : 'NINE' },  
  1 : { NAME: 'B' , PET :'CAT' , AGE : 'TEN' },  
  2 : { NAME: 'C' , PET :'TURTLE' , AGE : '' }  
}

Html :

<option ng-repeat='data in array' value="data.NAME"> {{data.PET}} </option>

So, if second(index) option is selected and click on a save button. I want to show an error saying age is empty.

I have an access to only Name because of value with val() and PET with text() in :selected

How to show an error if age is empty

2

Answers


  1. Few observations :

    • Your Array variable is not holding an array, It is holding an object.

    • Your ng-repeat syntax should be changed to handle the object of objects.

      <option ng-repeat="(key, value) in Array" value="value.NAME">
        {{value.PET}}
      </option>
      

    On submit, You can check for AGE field value from the Array object against this selected value (value.NAME).

    Live Demo :

    const obj = {
        0 : { NAME: 'A' , PET :'DOG' , AGE : 'NINE' },
        1 : { NAME: 'B' , PET :'CAT' , AGE : 'TEN' },
        2 : { NAME: 'C' , PET :'TURTLE' , AGE : '' }
    }
    
    const selectedValue = 'C';
    
    Object.keys(obj).forEach(key => {
        Object.keys(obj[key]).forEach(innerObjKey => {
        if (innerObjKey === 'NAME' && obj[key][innerObjKey] === selectedValue) {
            !obj[key].AGE ? console.log('Age not found!') : console.log('Age found!')
        }
      })
    })
    Login or Signup to reply.
  2. You can just search for the right object by NAME using array .find() method, then check over the AGE value of this one, if it exists:

    let searchedObj = Object.values(obj).find(o => o['NAME'] === selectedValue);
    
    if(searchedObj !== null && !searchedObj['AGE']){
          console.log('Age is empty!');
    }
    

    Demo:

    const obj = {
        0 : { NAME: 'A' , PET :'DOG' , AGE : 'NINE' },
        1 : { NAME: 'B' , PET :'CAT' , AGE : 'TEN' },
        2 : { NAME: 'C' , PET :'TURTLE' , AGE : '' }
    }
    
    const selectedValue = 'C';
    
    let searchedObj = Object.values(obj).find(o => o['NAME'] === selectedValue);
    
    if(searchedObj !== null && !searchedObj['AGE']){
          console.log('Age not found!');
    }

    Note:

    And make sure to arrange your ng-repeat to handle objects instead of array, because you have an object here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search