1

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: {}
  }
}
1
  • So you don't want SST in the final array? Commented Jul 22, 2022 at 19:36

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.