简体   繁体   中英

I am trying to check if given value exist as key in array of objects

I am trying to check if given value exist as key in array of objects

var obj = [{
  tapCount1: '10'
}, {
  tapCount2: '500'
}, {
  tapCount3: '1250'
}, {
  tapCount4: '1250'
}, {
  wtOfSample: '41.00'
}, {
  initialVolume: '66.0'
}, {
  tapCountvol1: '60.0'
}, {
  tapCountvol2: '53.0'
}, {
  tapCountvol3: '52.0'
}, {
  tapDensity: '0.788'
}, {
  compressibilityIndex: '21.212'
}, {
  hausnerRatio: '1.269'
}];

i had use below code

if (arrTDTData.hasOwnProperty("tapCount1") == false) {
  count1 = 0;
} else {
  count1 = arrTDTData.tapCount1;
}

i want to check if key is equal tapCount1 then it will return true else flase```

If you want to check if there is an object in the array that has tapCount1 key, you can use some() .

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

 var obj = [{"tapCount1":"10"},{"tapCount2":"500"},{"tapCount3":"1250"},{"tapCount4":"1250"},{"wtOfSample":"41.00"},{"initialVolume":"66.0"},{"tapCountvol1":"60.0"},{"tapCountvol2":"53.0"},{"tapCountvol3":"52.0"},{"tapDensity":"0.788"},{"compressibilityIndex":"21.212"},{"hausnerRatio":"1.269"}]; var result = obj.some(o => "tapCount1" in o); console.log(result); 

Use includes with map and Object.keys (and reduce to flatten the array):

 var obj = [{tapCount1:'10'},{tapCount2:'500'},{tapCount3:'1250'},{tapCount4:'1250'},{wtOfSample:'41.00'},{initialVolume:'66.0'},{tapCountvol1:'60.0'},{tapCountvol2:'53.0'},{tapCountvol3:'52.0'},{tapDensity:'0.788'},{compressibilityIndex:'21.212'},{hausnerRatio:'1.269'}]; const res = obj.map(Object.keys).reduce((acc, curr) => acc.concat(curr)).includes("tapCount1"); console.log(res); 

You can also use some on the array itself with hasOwnProperty (to avoid scanning the prototype):

 var obj = [{tapCount1:'10'},{tapCount2:'500'},{tapCount3:'1250'},{tapCount4:'1250'},{wtOfSample:'41.00'},{initialVolume:'66.0'},{tapCountvol1:'60.0'},{tapCountvol2:'53.0'},{tapCountvol3:'52.0'},{tapDensity:'0.788'},{compressibilityIndex:'21.212'},{hausnerRatio:'1.269'}]; const res = obj.some(e => e.hasOwnProperty("tapCount1")); console.log(res); 

You could get a single object and check the wanted property.

 var array = [{ tapCount1: '10' }, { tapCount2: '500' }, { tapCount3: '1250' }, { tapCount4: '1250' }, { wtOfSample: '41.00' }, { initialVolume: '66.0' }, { tapCountvol1: '60.0' }, { tapCountvol2: '53.0' }, { tapCountvol3: '52.0' }, { tapDensity: '0.788' }, { compressibilityIndex: '21.212' }, { hausnerRatio: '1.269' }], tapCount1 = 'tapCount1' in Object.assign({}, ...array); console.log(tapCount1); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM