Q:

Get value from child Array with a given ID

I have the following Array and I'm trying to print the child array value using .find by providing an ID
connections = [
    {
      group: 'a',
      items: [
        {
          id: '1',
          name: 'Andre'
        },
        {
          id: '2',
          name: 'David'
        }
      ]
    },
    {
      group: 'b',
      items: [
        {
          id: '3',
          name: 'Brandon'
        }
      ]
    },
]

I have tried the following in my Angular app, 
getUser(id) {
    this.activeItem = this.connections.items.find(data => data.id === id);
    console.log(this.activeItem);
}

I'm providing the correct ID but I'm getting an error saying,

error TS2339: Property 'items' does not exist on type....

Thank you. 

A:

You can use filter and some  methods.  This approach will filter array and your array will contain only desired items:

let connections = [
    {
      group: 'a',
      items: [
        {
          id: '1', name: 'Andre'
        },
        {
          id: '2', name: 'David'
        }
      ]
    },
    {
      group: 'b',
      items: [
        {
          id: '3', name: 'Brandon'
        }
      ]
    },
]

let id = 3;
// ONE WAY
const result = connections.filter(f=> f.items.some(s=> s.id == id))
                          .flatMap(fm => fm.items);
console.log(`result: `, result);

// OR ANOTHER WAY:
const resultWithGroup = connections.filter(f=> f.items.some(s=> s.id == id));
const resultItem = Object.assign({}, ...resultWithGroup).items.find(f => f.id == id);
console.log(`resultItem: `, resultItem);
console.log(`resultItem as an array: `, [resultItem]);

In addition, it is possible to use flatMap method.  By using this approach you are getting all items with desired id and then find the first element with id == 3:

let connections = [
    {
      group: 'a',
      items: [
        {
          id: '1', name: 'Andre'
        },
        {
          id: '2', name: 'David'
        }
      ]
    },
    {
      group: 'b',
      items: [
        {
          id: '3', name: 'Brandon'
        }
      ]
    },
]

const result = connections.flatMap(f => f.items).find(f => f.id == id);
console.log(`result as array`, [result]);

