Home > Back-end >  JavaScript Objects response mapping
JavaScript Objects response mapping

Time:11-02

REQUEST:

 
[
  {
    "realName": "OnlineOrderDoc-1",
    "preparedBy": "Jack"
  },
  {
    "realName": "GroceryBillDoc-2",
    "preparedBy": "Jill"
  },
  {
    "realName": "makingChargeDoc-2",
    "preparedBy": "John"
  },
  {
    "realName": "GroceryBillDoc-3",
    "preparedBy": "Sam"
  },
  {
    "realName": "makingChargeDoc-3",
    "preparedBy": "Bill"
  }
]

RESPONSE


[
  {
      "OnlineOrderDoc": {
        "preparedBy": "Jack"
      }
  },
  {
      "GroceryBillDoc": {
          "preparedBy": "Jill"
      },
      "makingChargeDoc": {
          "preparedBy": "John"
      }
  },
  {
      "GroceryBillDoc": {
          "preparedBy": "Sam"
      },
      "makingChargeDoc": {
          "preparedBy": "Bill"
      }
  }
]

I'm trying to write a function in JS to get the response in the format above. Basically, the function should iterate over response and create Objects within Array Response.
Ex: If Request has n Objects with realName key that ends in `-2`, then the response Object should have n Objects within the response Object
NOTE: Request and Response are listed above

I tried using a Map and check if there's an Object within it but it is never falling into else block. I'm open to any other solutions that can get the response

const result = (request) => {
const map = new Map();
request.forEach(req => {
const [newName, numberFromName] = req.realName.split('-');
if (map.has(newName)) {
                const current = map.get(name);
                map.set(newName, {current, ...{[newName]: filename}})

            } else {
                map.set(newName, filename)
            }
 }
}

CodePudding user response:

I would use a reduce which iterates over the request array. For each element curr, it splits the newName and numberFromName from the realname string. We can use the number to index acc and add the newName property to the object at that position.

const response = request.reduce((acc, curr) => {
  const [newName, numberFromName] = curr.realName.split('-');
  acc[numberFromName] = {
    ...acc[numberFromName],
    [newName]: {
      preparedBy: curr.preparedBy
    }
  }
  return acc
}, [])
  • Related