1

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}
4
  • 1
    userDetail[0] not working? Commented Oct 11, 2020 at 8:30
  • why not take the object with an index? Commented Oct 11, 2020 at 8:30
  • 1
    const [obj] = yourArray; Commented Oct 11, 2020 at 8:31
  • this.setState({user: {...filteredUser[0]}}); Commented Oct 11, 2020 at 8:58

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

you can use find

let userSelected = userDetail.find(x=>x.id === '12347442');

Comments

1

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}

2 Comments

No offence, but this tremendously inefficient - and what's more important, not really readable. Why do you use filter when find is fit? Why do you copy your found object - not once, but twice? Do you know that with ... you'll have only a shallow copy of an object? And why do you post your own code as an answer when it's essentially the same of one of existing ones?
These codes are both different a bit and not sufficient yet. Anyway, thanks man. I accept your suggestion. I am gotta change filter to find method.
0

if your array length=1 you must get userDetail[0]

1 Comment

got it. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.