-1

I have an array of object - like this -

test: [
{
 id:'1',
 name:'A'
},
{
 id:'2',
 name:'B'
},
]

Suppose I have a value 2 that exists in object Test as id. I want to get whole object from array if id value exists in whole array

input - 2,

expected output - {id:'2' , name:'B'}

How Can we get it ? is it any possible solution ?

Anurag Mishra
  • 647
  • 3
  • 15
  • 31
  • You would use `filter` function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter or `find`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find – Christian Nov 04 '20 at 09:04
  • 1
    use [find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) method: `array.find(obj => obj.id == input)` – Yousaf Nov 04 '20 at 09:05
  • 4
    Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – Billy Brown Nov 04 '20 at 09:05

2 Answers2

1

Simply use find-

const val = [
    {
        id: '1',
        name: 'A',
    },
    {
        id: '2',
        name: 'B',
    },
];
const res = val.find(obj => obj.id === '2');
console.log(res);
Chase
  • 5,315
  • 2
  • 15
  • 41
1

There can be multiple ways to do this. Here is how I did it.


let test = [
    {
        id: '1',
        name: 'A'
    },
    {
        id: '2',
        name: 'B'
    }
];

let result = (param) => test.filter(el => {
    return el.id == param
});

console.log(result(2))
Harsha Limaye
  • 915
  • 9
  • 29
  • `filter()` returns an array of all matching objects and not the object itself as the OP is asking. – pilchard Nov 04 '20 at 09:16
  • 1
    @pilchard `.filter()` method will work but as you rightly pointed out, it will return an array instead of the object itself but more importantly, Its not the right method to use in this case because it will unnecessarily iterate over the whole array even if the target object has already been found. `find()` or `findIndex()` methods will stop as soon as they find the target object. – Yousaf Nov 04 '20 at 09:18
  • Fair enough. I tried to put in duplicate ids and make it work. I guess id can be assumed to be unique. – Harsha Limaye Nov 04 '20 at 10:00