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

215
Visualizações
transform an array of objects into an array of objects with a different format

There is a use case whereby data needs to be transformed into result for the purpose of displaying the data in the UI in a pivoted format. In result the numbered keys are the month numbers and their values are the quantity for that month.

const data = [
            { date: '10/1/2021', quantity: 47 },
            { date: '11/1/2021', quantity: 58 },
            { date: '12/1/2021', quantity: 96 },
            { date: '1/1/2022', quantity: 88 },
            { date: '2/1/2022', quantity: 90 },
        ];

const result = [
            { year: 2021, 10: 47, 11: 58, 12: 96 },
            { year: 2022, 1: 88, 2: 90 }
        ];

So far I have created intermediate but don't know how to get that into the final result format in a concise manner. ES6 solutions are preferred.

const data = [
    { date: '10/1/2021', quantity: 47 },
    { date: '11/1/2021', quantity: 58 },
    { date: '12/1/2021', quantity: 96 },
    { date: '1/1/2022', quantity: 88 },
    { date: '2/1/2022', quantity: 90 },
];

const intermediate = data.map(o => {
    // eslint-disable-next-line no-unused-vars
    const [month, day, year] = o.date.split('/');    // destructuring assignment
    return { year: year, [month]: o.quantity }
});

console.log(intermediate);

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Updated: from intermediate to result

const intermediate = [
  { '10': 47, 'year': '2021' },
  { '11': 58, 'year': '2021' },
  { '12': 96, 'year': '2021' },
  { '1': 88, 'year': '2022' },
  { '2': 90, 'year': '2022' }
]

const yearDataMap = {}
intermediate.forEach(dto => {
  const storageObj = {} // temp store object

  Object.entries(dto).forEach(([key, value]) => { // destructure object props
    if(key === 'year') {
      storageObj['year'] = value
    }else {
      storageObj['month'] = key
      storageObj['quantity'] = value
    }
  })

  const {year, month, quantity} = storageObj 

  if (!yearDataMap[year]){ // if no entries with this year preset it with year record
    yearDataMap[year] = { year } // same as = { year: year }
  }

  yearDataMap[year][month] = quantity
})

const yearsArr = Object.values(yearDataMap)

console.log(yearsArr)

From given to result:

const data = [
  { date: '10/1/2021', quantity: 47 },
  { date: '11/1/2021', quantity: 58 },
  { date: '12/1/2021', quantity: 96 },
  { date: '1/1/2022', quantity: 88 },
  { date: '2/1/2022', quantity: 90 },
];

const yearDataMap = {} // map to store dates by year

data.forEach(dto => {
  const {date, quantity} = dto
  const [month, day, year] = date.split('/')

  if (!yearDataMap[year]){ // if no entries with this year preset it with year record
    yearDataMap[year] = { year } // same as = { year: year }
  }

  yearDataMap[year][month] = quantity // adding quantity  by month
})

const yearDataArr = Object.values(yearDataMap) // get rid of map and get the `result`

console.log(yearDataArr)

about 4 years ago · Juan Pablo Isaza Relatório

0

your approach was not bad. i built on it. the goal was to fill a global object. that was it.

globalObj = {}
data = [
  { date: '10/1/2021', quantity: 47 },
  { date: '11/1/2021', quantity: 58 },
  { date: '12/1/2021', quantity: 96 },
  { date: '1/1/2022', quantity: 88 },
  { date: '2/1/2022', quantity: 90 },
];

data.forEach((o) => {
  [month, day, year] = o.date.split('/'); 
  
  if (!globalObj[year]) {
    globalObj[year] = { year }    
  }
    globalObj[year][month] = o.quantity    
})
const result = Object.values(globalObj)
console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

A way to get from intermediate to result:

const data = [
    { date: '10/1/2021', quantity: 47 },
    { date: '11/1/2021', quantity: 58 },
    { date: '12/1/2021', quantity: 96 },
    { date: '1/1/2022', quantity: 88 },
    { date: '2/1/2022', quantity: 90 },
];

const intermediate = data.map(o => {
    // eslint-disable-next-line no-unused-vars
    const [month, day, year] = o.date.split('/');    // destructuring assignment
    return { year: year, [month]: o.quantity }
});

let years = [...new Set(intermediate.map(o => o.year))];
let accumulator = Object.assign({}, ...years.map(year => ({[year]: {}})));

intermediate.forEach(o => {
    accumulator[o.year] = { ...accumulator[o.year], ...o };
});

const result = Object.values(accumulator);
console.log(result);

But the above contained more individual steps than necessary. Ended up doing this -

const data = [
    { date: '10/1/2021', quantity: 47 },
    { date: '11/1/2021', quantity: 58 },
    { date: '12/1/2021', quantity: 96 },
    { date: '1/1/2022', quantity: 88 },
    { date: '2/1/2022', quantity: 90 },
];

accumulator = {};

data.forEach(o => {
    // eslint-disable-next-line no-unused-vars
    const [month, day, year] = o.date.split('/');    // destructuring assignment
    accumulator[year] = { ...accumulator[year], year: year, [month]: o.quantity };
});

const result = Object.values(accumulator);
console.log(result);

about 4 years ago · Juan Pablo Isaza 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