Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an object in array and taking values from that to present in a select list

Tags:

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.

like image 461
BeeNag Avatar asked Sep 01 '16 11:09

BeeNag


People also ask

How do you find a specific object in an array?

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.

How do you get a specific object from an array in React?

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.

How do you find the index of an object in an array of objects?

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.

How do you find the index of an object in an array in TypeScript?

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.


1 Answers

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.

like image 89
Igorsvee Avatar answered Oct 12 '22 08:10

Igorsvee