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?
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; }
Below is another approach.
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.
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))