I have a string value (e.g. "Table 1") that I need to use to find a specific object in an array that looks like so:
[ { lookups: [], rows: [{data: {a: 1, b: 2}}, {data: {a: 3, b: 4}}], title: "Table 1", columns: [{name: "a"}, {name: "b"}] }, { lookups: [], rows: [{data: {c: 5, d: 6}}, {data: {c: 7, d: 8}}], title: "Table 2", columns: [{name: "c"}, {name: "d"}] } ]
Once I have found that object I then need to take the values from the columns key and display them in a select list.
I know how to do the second part, but it is getting access to the object in the first place that I am having trouble with. I am trying to do this within a React component render.
Any help with this would be greatly appreciated.
Thanks for your time.
Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
To find an object in an array in React: Call the find() method on the array, passing it a function. The function should return an equality check on the relevant property. The find() method returns the first value in the array that satisfies the condition.
To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.
TypeScript - Array indexOf() indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
For the first part use find
method:
function findArrayElementByTitle(array, title) { return array.find((element) => { return element.title === title; }) }
It will return the first array element for which the condition element.title === title
holds true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With