Andy Tsao
Andy Tsao

Reputation: 33

How can I render an item from an array with a key

I have an array which stores data according to date, how can I render the data on a particular date?

I tried to use array[0].Data and it works, but what I really want to achieve is something like passing a prop "array(Jul)" and it shows the data in Jul. Is there a way to achieve this?

let array = [{Month: "Jul", Data: "this is my data", Place: "UK"},{Month: "Aug", Data: "this is my data2", Place: "USA"}] 

<View >
    <Text small bold white> {array(Jul).Data} </Text>
</View>

Upvotes: 0

Views: 30

Answers (2)

cuongtd
cuongtd

Reputation: 3182

You could convert the array to an object

let array = [{Month: "Jul", Data: "this is my data", Place: "UK"},{Month: "Aug", Data: "this is my data2", Place: "USA"}] 

const newData = array.reduce((acc, item) => (acc[item.Month] = item.Data, acc),{});

console.log(newData)
console.log(newData['Jul'])

and accress to Data like below

<View >
    <Text small bold white> {newData['Jul']} </Text>
</View>

Upvotes: 1

remeus
remeus

Reputation: 2424

You can use find:

array.find(x => x.Month === 'Jul').Data

Upvotes: 1

Related Questions