Home > Back-end >  How to loop through object and update its values in one line
How to loop through object and update its values in one line

Time:07-21

_shop: { [key: string]: string[] } = { fruits: ['Apple', 'Orange'], vegetables: ['Tomato', 'Onions'] }

Is there a one line code to return _shop with some modification in its values?

Which should have an output like this.

{
    "fruits": [
        {
            "name": "Apple",
            "isRotten": false
        },
        {
            "name": "Orange",
            "isRotten": false
        }
    ],
    "vegetables": [
        {
            "name": "Tomato",
            "isRotten": false
        },
        {
            "name": "Onions",
            "isRotten": false
        }
    ]
}

My attempt

myShop: { [key: string]: any } = {}

Object.keys(_shop).forEach((key) =>
    myShop[key] = _shop[key].map((item) => ({ name: item, isRotten: false }))
)

CodePudding user response:

Your snippet seems to get the job done, but if you really want only one statement you can do something like the following (for sake of readability I still will have some linebreaks)

myShop = Object.fromEntries(
  Object.entries(_shop).map(([k, v]) => 
    [k, v.map(item => ({name: item, isRotten: false}))]
  )
)

But IMHO I'd try to avoid such constructs, because they are pretty hard to read and therefore decrease maintainability ...

  • Related