Search code examples
javascriptarraysjavascript-objects

How to get an object from an array of objects with a specific value for a key?


For example, we have the following array of objects

[
{ x_id: 3, name: abc, class: 3rd, subject: maths},
{ x_id: 33, name: sad, class: 4th, subject: maths},
{ x_id: 12, name: fds, class: 3rd, subject: phy},
{ x_id: 4, name: atgr, class: 10th, subject: sst},
]

Output for x_id 4

{ x_id: 4, name: atgr, class: 10th, subject: sst}

Solution

  •     var array1 = [
        { x_id: 3, name: "abc", class: "3rd", subject: "maths" },
        { x_id: 33, name: "sad", class: "4th", subject: "maths" },
        { x_id: 12, name: "fds", class: "3rd", subject: "phy" },
        { x_id: 4, name: "atgr", class: "10th", subject: "sst" },
        { x_id: 4, name: "atgr", class: "12th", subject: "phy" }
    ]
    // returns the first element, that satisfies the provided testing function.
    let element = array1.find(element => element.x_id === 4);
    console.log(element);
    
    // returns the all elements, that satisfies the provided testing function.
    let results = array1.filter(element => element.x_id === 4);
    console.log(results);
    

    find()

    Use find() to search for the first Element, that satisfies the provided function ( element => element.x_id === 4 )

    let element = array1.find(element => element.x_id === 4);
    console.log(element);
    

    returns

    { x_id: 4, name: 'atgr', class: '10th', subject: 'sst' }
    

    filter()

    Use filter() to search for all objects that satisfies the provided function ( element => element.x_id === 4 )

    let results = array1.filter(element => element.x_id === 4);
    console.log(results);
    

    returns

    [ 
      { x_id: 4, name: 'atgr', class: '10th', subject: 'sst' },
      { x_id: 4, name: 'atgr', class: '12th', subject: 'phy' } 
    ]