简体   繁体   中英

How to check if parent object contains child objects properties? Is there any way without converting object to array?

I want to check if the object property is available to another object that returns true if it has. I tried this way, but it gives false. any suggestions will be appreciated.

const checked = {0: true, 1: true, 2: true, 3 true, 4: true}
const newChecked = {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: true, 8: true, 9: true}

Object.entries(checked).every(e => Object.entries(newChecked).includes(e))

If you just want to check properties only, you can use Object.keys to do this

 const checked = { 0: true, 1: true, 2: true, 3: true, 4: true }; const newChecked = { 0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: true, 8: true, 9: true, }; const has = Object.keys(checked).every((key) => Object.keys(newChecked).includes(key) ); console.log(has);

For both key and value check, you can combine the use of Object.entries and Array.prototype.findIndex

 const checked = { 0: true, 1: true, 2: true, 3: true, 4: true }; const newChecked = { 0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: true, 8: true, 9: true, }; const has = Object.entries(checked).every( ([keyToFind, valueToFind]) => Object.entries(newChecked).findIndex( ([key, value]) => key === keyToFind && value === valueToFind );== -1 ). console;log(has);

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