-2

I have an array of objects that looks like this...

const arr = [
{
    "id": 1,
    "name": "Bob",
    "age": 36
},
{
    "id": 2,
    "name": "Laura",
    "age": 24
}
{
    "id": 3,
    "name": "Michael",
    "age": 28
}
{
    "id": 4,
    "name": "Tim",
    "age": 54
}
]

I need javascript logic that can extract an object based on an id passed into it.

For example, if I pass in the number 4, it would return...

{
    "id": 4,
    "name": "Tim",
    "age": 54
}

since the id for that object matches the number 4. I think the solution involves .findIndex(), but I'm not able to figure out how to utilize that method into a solution.

Can anyone help?

Anil_M
  • 10,893
  • 6
  • 47
  • 74
Code Junkie
  • 83
  • 1
  • 15

2 Answers2

1

There are many ways to do this, but I think Array.filter() is the most elegant.

const arr = [
  { "id": 1, "name": "Bob", "age": 36 },
  { "id": 2, "name": "Laura", "age": 24 },
  { "id": 3, "name": "Michael", "age": 28 },
  { "id": 4, "name": "Tim", "age": 54 }
];

const extractObject = (id) => {
  return arr.filter(row => row.id === id).pop();
};

let laura = extractObject(2);

console.log(laura);
code_monk
  • 9,451
  • 2
  • 42
  • 41
0
function findInSet(recordSet, id){
    return recordSet.find(element => element.id == id);
}

Dinu
  • 1,374
  • 8
  • 21