Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

64
Visualizações
Parsing arrays of objects

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: {}
  }
}
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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)

about 4 years ago · Santiago Trujillo Relatório

0

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

about 4 years ago · Santiago Trujillo Relatório

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda