Home > Software engineering >  Parsing arrays of objects
Parsing arrays of objects

Time:07-23

I have this array of objects:

let rooms = [
    {
        room: "S2D", rate: "24"
    },
    {
        room: "S2D", rate: "23"
    },
    {
        room: "SEC", rate: "24"
    },
    {
        room: "SEC", rate: "23"
    },
    {
        room: "SST", rate: "24"
    },
    {
        room: "SST", rate: "23"
    }
];

I'm looking forward to achieve something like this:

{
    S2D: {
        24: {},
        23: {}
    },
    SEC: {
        24: {},
        23: {}
    }
}

I have tried doing this way but the output is not the same as expected. I'm have some trouble when adding the rates inside room objects even though I'm adding spread operator to keep the previous values.

rooms.map((elem, idx) => {
    let {room, rate} = elem;
    room_rates[room] = {};
    if(!room_rates[room]?.hasOwnProperty(rate)){
        room_rates[room] = {
            ...room_rates[room],
            [rate]:{}
        }
    }
})

OUTPUT

{
  S2D:{
    23: {}
  },
  SEC:{
    23: {}
  },
  SST:{
    23: {}
  }
}

CodePudding user response:

Here is a quick and simply way to do it using a basic foreach loop and checking to see if the key exists or not.

let rooms = [{
    room: "S2D",
    rate: "24"
  },
  {
    room: "S2D",
    rate: "23"
  },
  {
    room: "SEC",
    rate: "24"
  },
  {
    room: "SEC",
    rate: "23"
  },
  {
    room: "SST",
    rate: "24"
  },
  {
    room: "SST",
    rate: "23"
  }
]

let final = {};

rooms.forEach(function(x){
   if(!final[x["room"]]){final[x["room"]] = {};}
   final[x["room"]][x["rate"]] = {};   
});

console.log(final)

CodePudding user response:

You can transform the rooms array into the desired object using Array.prototype.reduce.

const rooms = [
  { room: "S2D", rate: "24" },
  { room: "S2D", rate: "23" },
  { room: "SEC", rate: "24" },
  { room: "SEC", rate: "23" },
  { room: "SST", rate: "24" },
  { room: "SST", rate: "23" },
];

const result = rooms.reduce(
  (acc, { room, rate }) => ({
    ...acc,
    [room]: { ...acc[room], [rate]: {} },
  }),
  {}
);

console.log(result);

CodePudding user response:

Understand the problem of your code first

here if(!room_rates[room]?.hasOwnProperty(rate)) you check for whether the object has a rate property , if and only if not then create one

instead of doing the above approach do something like this

if the room_rate has then simply create first then outside the condition add the value

in this way you can ensure that the room_rates have that room property before adding all the rooms to room_rates

  • Related