Title rewritten as: No matter what, I can't get a value from my array
P粉308783585
2023-08-18 15:22:01
<p>I'm trying to display data from an array in my React component. </p>
<p>I can see the data I need in the browser developer console via <code>console.log()</code>: </p>
<pre class="brush:php;toolbar:false;">FinalRecords.js::recordTitle: (4)
0: {members: Array(10), id: 62, title: 'RR 1980 Record 1', storeId: 1088}
1: {members: Array(10), id: 63, title: 'RR 1980 Record 2', storeId: 1088}
2: {members: Array(10), id: 64, title: 'RR 1980 Record 3', storeId: 1088}
3: {members: Array(10), id: 65, title: 'RR 1980 Record 4', storeId: 1088}
length: 4
[[Prototype]]: Array(0)</pre>
<p>But I can't seem to figure out how to get the <code>title</code>. </p>
<p>I've tried a lot of different things, this one being the most recent: </p>
<pre class="brush:php;toolbar:false;">render() {
const { recordId, records, bandName } = this.props;
var data = records.filter((r) => r.id === recordId);
var records = data.toArray();
console.log("FinalRecords.js :: recordTitle: ", records);
return <div> record - {findRecordTitle(records, recordId) } - {bandName || ''} </div>
}
}
function findRecordTitle(records, id) {
return records.find((record) => {
return record.id === id;
})
}</pre>
<p>I need to get the <code>title</code> of the record by using <code>id</code>. </p>
<p>But it's always blank. </p>
<p>Did I do something wrong? </p>
The name of this function means you expect it to return a "title" (which I would interpret as a string value):
However, nowhere in this function does it have anything to do with "title". It returns a matching object (or
null
) in therecords
array. If you just want to return thetitle
property of the object, just return the property:EDIT: If your JavaScript environment is unable to use optional chaining, you can explicitly check for
null
before trying to use the object:Or it can default to an empty string instead of
null
etc.