Reputation: 1251
I have an array of Objects and a search function. The search function takes in a user name and passes it to the profile render component which finds the user name and returns their data. My problem right now, is I am using a conditional if block to search the array and return results. This causes any user profile past the [0] spot in the array to have additional
tags which cause extra spacing.
Is there a way I can just loop through the array and return only the 1 I want? I'am assuming that I might need to make a varible that handles the 1 true return then only return that.
Here is what I have so far.
const renderUser = this.props.data.map( (obj, idx) => {
return (
this.props.name === obj.name ?
<p key={idx}>
Name: {obj.name} < br/>
Email: {obj.email} <br />
Flavor: {obj.flavor} <br />
STR: {obj.str} <br />
AGI: {obj.agi} <br />
INT: {obj.int} <br />
STA: {obj.sta} <br />
</p>
:
<p key={idx}> </p>
)
});
I can clean it up a little by adding a var to handle the data, but this causes the each element in an array needs a key error.
const renOneUser = this.props.data.map(( obj, idx ) => {
let userData;
this.props.name === obj.name ?
userData = <p key={idx}>
Name: {obj.name} < br/>
Email: {obj.email} <br />
Flavor: {obj.flavor} <br />
STR: {obj.str} <br />
AGI: {obj.agi} <br />
INT: {obj.int} <br />
STA: {obj.sta} <br />
</p>
:
<p key={idx}> </p>
return (
<div>
{userData}
</div>
)
});
Upvotes: 0
Views: 2657
Reputation: 2584
you can use the filter
function, to filter by a condition, and then pass the results through the map
function:
this.props.data.filter(obj => {
return this.props.name === obj.name;
}).map((obj, idx) => {
return (
<p key={idx}>
Name: {obj.name} < br/>
Email: {obj.email} <br />
Flavor: {obj.flavor} <br />
STR: {obj.str} <br />
AGI: {obj.agi} <br />
INT: {obj.int} <br />
STA: {obj.sta} <br />
</p>
);
});
Upvotes: 1