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

98
Visualizações
How do i push same object value in to an array

I've been trying to deal with the json below for a few days.

[
  {createdAt: "2021-09-09 07:37", user_id: "admin", type: "click", query: "spider"},
  {createdAt: "2021-09-09 07:37", user_id: "admin", type: "search", query: "spider"},
  {createdAt: "2021-09-09 07:38", user_id: "user", type: "click", query: "hi"},
]

If a certain value is duplicate, I want to add it to a new array. like this

[
  {
    createdAt: "2021-09-09 07:37", 
    user_id: "admin",
    query: "spider",
    type: "click",
    result: [
     {createdAt: "2021-09-09 07:37", user_id: "admin", type: "search", query: "spider"}
    ]
  },
  {createdAt: "2021-09-09 07:38", user_id: "user", type: "click", query: "hi"}
]

The groupBy function of lodash is the most similar, but I am not familiar with JavaScript.
anyone can help me how to handling those json?

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

0

You can easily achieve the result using Map, and forEach

const arr = [
  {
    createdAt: "2021-09-09 07:37",
    user_id: "admin",
    type: "click",
    query: "spider",
  },
  {
    createdAt: "2021-09-09 07:37",
    user_id: "admin",
    type: "search",
    query: "spider",
  },
  {
    createdAt: "2021-09-09 07:38",
    user_id: "user",
    type: "click",
    query: "hi",
  },
];

let map = new Map();

arr.forEach((obj) => {
  const { user_id, createdAt } = obj;
  if (map.has(`${user_id}|${createdAt}`))
    map.get(`${user_id}|${createdAt}`).push(obj);
  else map.set(`${user_id}|${createdAt}`, [obj]);
});

const result = [];
for (let [, v] of map) {
  const [first, ...rest] = v;
  const temp = Object.assign({}, first);
  if (rest.length) temp.result = rest;
  result.push(temp);
}

console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Relatório

0

Below is another approach.

  1. uses one Array.reduce to build one dictionary to store how many times the key occurs and where to save the data of the key.

  2. uses another Array.reduce to loop all elements then apply your logic.

const data = [
  {createdAt: "2021-09-09 07:37", user_id: "admin", type: "click", query: "spider"},
  {createdAt: "2021-09-09 07:37", user_id: "admin", type: "search", query: "spider"},
  {createdAt: "2021-09-09 07:38", user_id: "user", type: "click", query: "hi"},
]

function relayout() {
  const indexes = data.reduce((pre, cur) => {
    pre[`${cur.createdAt}-${cur.user_id}`] = [0, 0] // count, position in result array
    return pre
  }, {})
  return data.reduce((pre, cur) => {
    const key = `${cur.createdAt}-${cur.user_id}`
    if (indexes[key][0] > 0) {
      pre[indexes[key][1]].result = [
        ...(pre[indexes[key][1]].result || []),
        cur
      ]
    } else {
      pre.push(cur)
      indexes[key][1] = pre.length - 1
    }
    indexes[key][0] += 1
    return pre
  }, [])
}

console.log(relayout(data))

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