-4

I want to search in an object that has objects inside it

My object looks like this:

let foo = {
65:{
    foo: 'bar',
    bar: 'amet',
    dolor: 'foo'
},
66:{
    foo: 'foo',
    bar: 'sit',
    dolor: 'amet'
},
70:{
    foo: 'amet',
    lorem: 'amet',
    bar: 'sit'
}
}

I want a search function that searches through all values of all objects inside foo And then return a list of numbers of results

e.g. if I search for 'o' I want this to be returned:

[65,66]

Because the 65 & 66 has 'o' inside their values

amiria703
  • 74
  • 10
  • Does this answer your question? [JS search in object values](https://stackoverflow.com/questions/8517089/js-search-in-object-values) – ikiK Mar 12 '21 at 18:41
  • Nope, the all search in a list that has objects inside, but mine is an object that has objects inside – amiria703 Mar 12 '21 at 18:43

2 Answers2

1

You can use flatMap by taking the entries of that object

const foo = {65:{ foo: 'bar', bar: 'amet', dolor: 'foo'},66:{ foo: 'foo', bar: 'sit', dolor: 'amet'},70:{ foo: 'amet', lorem: 'amet', bar: 'sit'}};

const result = Object.entries(foo).flatMap(([num,val])=>Object.values(val).some(t=>t.includes('o')) ? +num : []);

console.log(result);
gorak
  • 5,233
  • 1
  • 7
  • 19
1

You could get the keys from the object and filter the nested values by the given string.

const
    getKeys = (object, string) => Object
        .keys(object)
        .filter(k => Object.values(object[k]).some(v => v.includes(string))),
    foo = { 65: { foo: 'bar', bar: 'amet', dolor: 'foo' }, 66: { foo: 'foo', bar: 'sit', dolor: 'amet' }, 70: { foo: 'amet', lorem: 'amet', bar: 'sit' } };

console.log(getKeys(foo, 'o'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392