-2

Hello everyone I am searching how to search inside a big object and all results are some small objects wit only children and not any grandchildren

my question is

let obj = {
  child1: {
    name: 'Nairi',
    age: 19
  },
  child2: {
    name: 'Zara',
    age: 19
  },
  child3: {
    name: 'Tyom',
    age: 20
  }
}

I want to get entire child 3 if I'm searching for Tyom and child1 if for Nairi so that I could access other keys like their age etc...

1 Answers1

0

You can use Object.values() to get an array of all your values from your object, and then use .find() on those values to find the child object which has a name property equalling your search:

let obj = { child1: { name: 'Nairi', age: 19 }, child2: { name: 'Zara', age: 19 }, child3: { name: 'Tyom', age: 20 } }

const search = "Tyom";
const res = Object.values(obj).find(child => child.name === search);
console.log(res);

However, your outer object seems like it would be better suited for an array, as you seem to be storing a list of children, which in this case wouldn't require the need for Object.values() and can be done just using .find():

let children = [{ name: 'Nairi', age: 19 }, { name: 'Zara', age: 19 }, { name: 'Tyom', age: 20 }];

const search = "Tyom";
const res = children.find(child => child.name === search);
console.log(res);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • 1
    Oh no sorry, the problem is that mine isn't in an array and I don't have any way to push it inside one :/ – Nairi Areg Hatspanyan Jul 17 '20 at 01:58
  • @NairiAregHatspanyan the first code snippet deals with an object, the second code snippet deals with an array. If you have to use an object then you should be able to use the first example – Nick Parsons Jul 17 '20 at 02:07