I have a problem in reducing an object which contains array into a simple array. I have a backend which returns a list of dogs and their price. The way the api returns the data, seems really difficult to work with and I am struggling to convert the object into an array. I have tried turning into an array and reducing it.
Here is an example - I want to convert the following object:
const a = {
dogs: [
{
"id": "dog1",
"priceRange": [
"low",
"high"
],
"vaccinated": true,
},
{
"id": "dog2",
"priceRange": [
"low",
"high"
],
"vaccinated": false,
}
],
"cost": [
{
"id": "low",
"cost": 200,
},
{
"id": "mid",
"cost": 400,
},
{
"id": "high",
"cost": 600,
}
]
};
into this array:
const reducedArray = [
{
"id": "dog1",
"priceRange": [
{
"id": "low",
"cost": 200,
},
{
"id": "high",
"cost": 600,
}
],
"vaccinated": true,
},
{
"id": "dog2",
"priceRange": [
{
"id": "low",
"cost": 200,
},
{
"id": "high",
"cost": 600,
}
],
"vaccinated": false,
}
]
I am not sure
CodePudding user response:
You need to iterate over your a.dogs
array first and within each iteration, also iterate over the priceRange array and find its corresponding value inside the a.cost
array and return that instead of the string low or high.
a.dogs.map(dog => ({
...dog,
priceRange: dog.priceRange.map(priceRange => a.cost.find(cost => cost.id === priceRange))
}))
CodePudding user response:
- Using
Array#reduce
, iterate overa.cost
while updating aMap
where the key is theid
and value is the object - Using
Array#map
, iterate overa.dogs
and set thepriceRannge
items from the Map using anotherArray#map
iteraion
const a = {
"dogs": [ { "id": "dog1", "priceRange": [ "low", "high" ], "vaccinated": true }, { "id": "dog2", "priceRange": [ "low", "high" ], "vaccinated": false } ],
"cost": [ { "id": "low", "cost": 200 }, { "id": "mid", "cost": 400 }, { "id": "high", "cost": 600 } ]
};
const costMap = a.cost.reduce((map, cost) =>
map.set(cost.id, cost)
, new Map);
const reducedArray = a.dogs.map(dog => ({
...dog,
priceRange: dog.priceRange.map(range => {
const { id, cost } = costMap.get(range) || {};
return { id, cost};
})
}));
console.log(reducedArray);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>