Skip to content
Advertisement

Is there a .contains method in javascript that works similar to Python’s implimentation .__contains__()? – node.js

I’m wondering if there is any implimentation of a object.contains method in javascript that works similar to how the Python version object.__contains__() works, as in I want to be able to scan the whole object with nested objects to see if there is either a key or a value that does contain what the method is comparing it against. I know there are other ways in Javascript to do this such as using filter and some, but they don’t work for me.

person: {
  name: 'Bob',
  age: 40,
  items: {
    cars: 4,
    house: 1,
    computer: 2
  }
}

I need something that scans the WHOLE object rather than just the first level of it (which would be name, age, and items, and if you searched for cars you wouldn’t get any response).

Advertisement

Answer

I don’t think so. A naive take would be

JSON.stringify(target).includes( JSON.stringify( search ) )

It doesn’t work well if search is not a string though, as that will also match also inside strings. A non naive approach would be something like this:

const contains = (obj, search) => 
 Object.keys(obj).includes(search) ||
 Object.values(obj).includes(search) ||
 Object.values(obj)
   .filter(it => typeof it === "object" && it !== null)
   .some(it => contains(it, search));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement