Search code examples
arraysangulartypescriptjavascript-objects

Find items in the array based on the inner array condition


How to find id in an array that is inside of an array of objects

Example:

let arrayobjects = [{ 
    id: 1, 
    name: "oinoin", 
    description: ["one", "two", "three"]
}, { 
    id: 2, 
    name: "zatata", 
    description: ["four", "five", "six"]
}];

How can I find the id of the word "two" ?


Solution

  • If you need more than one item, you can filter the array via Array#filter, check if property description for each item contains word two via Array#includes (ES7), then map the result to get only id of those items using Array#map.

    let arrayobjects = [
          { id: 1, name: "oinoin", description: ["one", "two", "three"] }, 
          { id: 2, name: "zatata", description: ["four", "five", "six"] }
    ];
    
    const ids = arrayobjects.filter(item => item.description.includes('two'))
                            .map(item => item.id);
                            
    console.log(ids);

    If you have only one item, you can just use Array#find and do same checking

    let arrayobjects = [
          { id: 1, name: "oinoin", description: ["one", "two", "three"] }, 
          { id: 2, name: "zatata", description: ["four", "five", "six"] }
    ];
    
    const item = arrayobjects.find(item => item.description.includes('two'));
                            
    console.log(item.id);