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

find a word inside array propety inside object

How can i iterate this object, and his properties that have arrays, to fin a word that is inside of array, for example beats

[ { mouse: 'lenovo',
    teclado: 'dell',
    monitor: 'hp',
    headset: [ 'audioTechnica', 'klipXtreme', 'beats' ] },
  { mouse: 'razor',
    teclado: 'think pad',
    monitor: 'lg',
    headset: [ 'random', 'hyperx', 'jbl' ] },
  { mouse: 'technet',
    teclado: 'red dragon',
    monitor: 'benq',
    headset: [ 'sony', 'senheiser', 'toshiba' ] } ]

>Solution :

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

You want to find object in this array, which properties has some string, correct?

If that’s what you are looking for, here is some quick tip: you should iterate over array (maybe, using "find") and then for each object iterate over it’s props, and then check if it has a string you are looking for.

Implementation example:

let searchPhrase = 'razor';

array.find(item => {
  Object.keys(item).find(key => typeof item[key] === 'string' ? 
    item[key] === searchPhrase : 
    item[key].includes(searchPhrase)
  )
)

Please be aware that this code relies on the fact that the object’s properties are only string or array. If you are not sure about that fact, some additional checks required.

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