Skip to content
Advertisement

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?

Advertisement

Answer

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))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement