Reputation: 73
I have an array of objects:
let userDetail = [{id: "12347442", name: "ZarNi" , age: 23}
{id: "2435457", name: "Michael" , age: 13},
{id: "8639503", name: "John" , age: 18}
]
I filtered this array into this:
let filteredUser = userDetail.filter(user => user.id === "12347442");
I need to put object to react state. so I've written like this:
this.setState({user: {...filteredUser}});
When I took the console for user state,I've got the result like this:
console.log(this.state.user);
Result => {0:{id: "12347442", name: "ZarNi" , age: 23}} as a result;
I don't want Key 0. I just want to get object like this
{id: "12347442", name: "ZarNi" , age: 23}
Upvotes: 1
Views: 93
Reputation: 73
I changed my code like this and I've got the result that I want.
let userDetail = [{id: "12347442", name: "ZarNi" , age: 23},
{id: "2435457", name: "Michael" , age: 13},
{id: "8639503", name: "John" , age: 18}];
let user = userDetail.find(user => user.id === "12347442");
this.setstate({user: user});
console.log(this.state.user);
Result:
{id: "12347442", name: "ZarNi" , age: 23}
Upvotes: 1
Reputation: 106365
If all the records in your array have different IDs OR you expect to use the first match anyway, it's not filter
you need - but find
:
// const, as you're not expected to change value of that variable
const foundUser = userDetail.find(user => user.id === "12347442");
In this case you won't even have to worry about extracting the first element from that array which is result of filter
op - and pass that user into setState directly.
Upvotes: 2
Reputation: 873
you can use find
let userSelected = userDetail.find(x=>x.id === '12347442');
Upvotes: 1