I am struggling in try to display all marketids from a json. At the moment I have a foreach to return each event id and all its related data from within markets array like so:
export async function generateData() {
const matchArray = [];
try {
const data = await get(dataEndpoint);
data ? data.forEach((item) => {
if (item.type== 'MATCH'){
matchArray.push({ eventId: item.id, markets: [item.markets]});
}
}) : console.log(`No data received ${data}`);
await writeJSON(matchFilePath, matchArray);
} catch (error) {
throw error;
}
}
It writes the following in the json file:
[
{
"eventId": "b312bea8-c25b-43f2-85a3-1c6caa5230e4",
"markets": [
[
{
"id": "28e53502-8a44-467e-a5bc-d1d613597d26",
"createdAt": "2024-08-05T10:31:58.288Z"
},
{
"id": "28e53502-8a44-467e-a5bc-d1d613597d25",
"createdAt": "2024-08-05T10:31:58.288Z"
},
{
"id": "28e53502-8a44-467e-a5bc-d1d613597d21",
"createdAt": "2024-08-05T10:31:58.288Z"
}
]
]
},
{
"eventId": "b312bea8-c25b-43f2-85a3-1c6caa5230e4",
"markets": [
[
{
"id": "28e53502-8a44-467e-a5bc-d1d613597d16",
"createdAt": "2024-08-05T10:31:58.288Z"
},
{
"id": "28e53502-8a44-467e-a5bc-d1d613597d15",
"createdAt": "2024-08-05T10:31:58.288Z"
},
{
"id": "28e53502-8a44-467e-a5bc-d1d613597121",
"createdAt": "2024-08-05T10:31:58.288Z"
}
]
]
}
]
But ideally what I want is only all the ids within markets[] for each event, so based on the above json example I want it to be displayed like this:
[
{
"eventId": "b312bea8-c25b-43f2-85a3-1c6caa5230e4",
"markets": [
[
{
"id": "28e53502-8a44-467e-a5bc-d1d613597d26",
},
{
"id": "28e53502-8a44-467e-a5bc-d1d613597d25",
},
{
"id": "28e53502-8a44-467e-a5bc-d1d613597d21",
}
]
]
},
{
"eventId": "b312bea8-c25b-43f2-85a3-1c6caa5230e4",
"markets": [
[
{
"id": "28e53502-8a44-467e-a5bc-d1d613597d16",
},
{
"id": "28e53502-8a44-467e-a5bc-d1d613597d15",
},
{
"id": "28e53502-8a44-467e-a5bc-d1d613597121",
}
]
]
}
]
I’m not sure how pull only the market ids within the markets[] array. Curious to know how to do this.
2
Answers
When setting the
markets
property on your resulting objects here:You can
.map()
overitem.markets
to get just the value you want in that array. For example:Instead off pushing all the
markets
, alter to object to your liking.So
Can be replaced with something like:
Where we use
map()
to only keep theid