简体   繁体   中英

How to convert an object with arrays into an array

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

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))
}))
  • Using Array#reduce , iterate over a.cost while updating a Map where the key is the id and value is the object
  • Using Array#map , iterate over a.dogs and set the priceRannge items from the Map using another Array#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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM