Suppose I have an array:
{
"data": [
{
"id": 9,
"body": "This is the first body of text,
"availability": "internal",
"title": "Test",
"posted_by": "Test"
},
{
"id": 10,
"body": "This is the second body of text",
"availability": "internal",
"title": "TEST2",
"posted_by": "TEST2"
},
}
My aim is to be able to print a specific "title" or "body" in my React app. Previously I had the data in JSON where I could simply use something like data.title[0] which would be Test.
Now I pull data using the following code:
componentDidMount() {
axios
.get(
"API_KEY"
)
.then((res) => {
let data = res.data
this.setState({ data, loading: false });
console.log(data)
});
}
render() {
if (this.state.loading) {
return <Loader />
}
else
return (
this.state.data.data.map((item) => (
<>
<marquee direction="left" behaviour="scroll">
<p key={item.id}>{item.body} </p>
</marquee>
</>
))
And I can't find a way to print specific "title" or "body" values, only every output in the array.
Currently my only idea is to use .slice() to manipulate the data the way I want, but this seems like a dirty way of fixing my issue.
Any advice/guidance greatly appreciated, thanks!
Unpacking fields from objects passed as a function parameter can do this.
const user = {
id: 42,
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe'
}
};
function userId({id}) {
return id;
}
function whois({displayName, fullName: {firstName: name}}) {
return `${displayName} is ${name}`;
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment