I’m using react native and I have an array that looks like:
[
[
{
"__typename": "Todo",
"createdAt": "2023-07-15T01:19:56.489Z",
"description": null,
"id": "43696aa7-3244-44a9-abd0-3437be799121",
"name": "squat",
"reps": 12,
"updatedAt": "2023-07-15T01:19:56.489Z",
"weight": 135
},
{
"__typename": "Todo",
"createdAt": "2023-07-15T13:04:32.141Z",
"description": null,
"id": "616e19b9-4786-4b2e-bf11-7c54bd725e4b",
"name": "squat",
"reps": 1,
"updatedAt": "2023-07-15T13:04:32.141Z",
"weight": 135
}
]
]
I would like to get all of the "weights" from each array object into a separate array where it would look like:
[135, 135]
I tried doing arrayname.map((b,i) => b[i].weight)
but this only gave me the first objects weight so it looked like: [135]
Any help would be appreciated. I understand this might be a dumb question but I really don’t know how to do it.
3
Answers
To extract all the "weights" from each object in the array, you can use the map function to iterate over the array and access the "weight" property of each object. Here’s an example of how you can achieve this:
In the code above,
flatMap
is used to flatten the nested array into a single-level array. Then,map
is used to iterate over each object in the array and extract the "weight" property. Finally, the resulting weights are stored in the weights array.This will give you the desired result of
[135, 135]
.maybe like this:
Here your items are inside the child array. You can try the following.