Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

108
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda