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

91
Visualizações
Create an array of object properties for each item that has the same key

I'm merging two objects together to create a filter object. However I want to group the merged objects property values where the keys are the same.

So...

[{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}]

becomes

[{category: ['furniture', 'mirrors']}, {availability: 'in_stock'}]

any ideas?

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

0

With lodash you merge the entire array to a new object by spreading into _.mergeWith(). The customizer should use empty arrays as default values for the current values, and concat the values. Use _.map() to convert back to an array.

const data = [{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}];

const result = _.map(
  _.mergeWith({}, ...data, (a = [], b = [], key) => a.concat(b)),
  (val, key) => ({ [key]: val })
)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Using vanilla JS, reduce the array to a Map using the objects' keys as the keys of the Map, with an empty array as the value, and push the objects' values into the arrays. Use Array.from() to convert the Map to an array.

const data = [{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}];

const result = Array.from(
  data.reduce((acc, obj) => {
    Object.entries(obj)
      .forEach(([key, val]) => {
        if(!acc.has(key)) acc.set(key, [])

        acc.get(key).push(val)
      })

    return acc
  }, new Map()),
  ([key, val]) => ({ [key]: val })
)

console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use reduce like this:

const data = [
  { category: 'furniture' }, 
  { category: 'mirrors' }, 
  { availability: 'in_stock' }
];

const result = data.reduce(
  (a, x) => {
    const key = Object.keys(x)[0]; // find the key of the current object
    if (!a.tmp[key]) { // if the current key doesn't exist in the lookup object (tmp) yet ...
      a.tmp[key] = []; // create an empty array in the lookup object for the current key
      a.result.push({ [key]: a.tmp[key] }); // push the current object to the result
    }
    a.tmp[key].push(x[key]); // push the current value to the array
    return a;
  }, 
  { result: [], tmp: {} },
).result;

console.log(result);

I'm sure there are easier ways to achieve this, but that's the best I can come up with right now.

about 4 years ago · Juan Pablo Isaza Relatório

0

we can also achieve this by using forEach loop :

const input = [{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}];

const resultObj = {};
const resultArr = [];

input.forEach((obj) => {
  resultObj[Object.keys(obj)[0]] = [];
})

input.forEach((obj) => {
  resultObj[Object.keys(obj)[0]].push(obj[Object.keys(obj)[0]]);
  resultArr.push(resultObj);
})

console.log([...new Set(resultArr)]);

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