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

Time:09-02

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}

CodePudding user response:

    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' } 
]

CodePudding user response:

You can do this with .find() for example this is your array

const array = [
{ 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'},
];

With this method you will iterate and find the element you are looking for within array

var result = array.find(x => x.x_id === 4);
console.log(result); //returns { x_id: 4, name: 'atgr', class: '10th', subject: 'sst'}

https://jsfiddle.net/kenpy/0uj2eo4f/3/

  • Related