I would like to add key and values to my objects in resultLog, and I've tried couple of different things but haven't got it to work. (see further down what I would like to achieve).
This is my output so far:
I have pushed my array into objects and added keys.....but now Im stuck.
let result = [5, 4, 1, 1];
let resultLog = [];
for (let i = 0; i < result.length - 1; i += 2) {
resultLog.push({ pageViews: result[i], visitors: result[i + 1] });
}
console.log(resultLog);
// output [{pageViews: 5, visitors: 4},{ pageViews: 1, visitors: 1}]
I need to add key and value to each object, but how can I do that? I've had a look at .splice
or .unshift
but can't get it to work.
This is what I would like it to look like:
let result = [
{ url: "/contac.html", pageViews: 5, visitors: 4 },
{ url: "/home.html", pageViews: 1, visitors: 1 }
];
console.log(result)
console.table(result);
This is the array that I extracted the number of unique users of each url and number of pageViews.
const filtered =[
"|2019-03-01 09:00:00UTC |/contact.html |12345 |",
"|2019-03-01 09:00:00UTC |/contact.html |12346 |",
"|2019-03-01 10:00:00UTC |/contact.html |12345 |",
"|2019-03-01 10:30:00UTC |/home.html |12347 |",
"|2019-03-01 11:00:00UTC |/contact.html |12347 |",
"|2019-03-02 11:00:00UTC |/contact.html |12348 |"]
You can try this
var obj= {array:[]};
for (let i = 0; i < result.length - 1; i += 2) {
obj.array.push({ pageViews: result[i], visitors: result[i + 1] });
}
const filtered = [
"|2019-03-01 09:00:00UTC |/contact.html |12345 |",
"|2019-03-01 09:00:00UTC |/contact.html |12346 |",
"|2019-03-01 10:00:00UTC |/contact.html |12345 |",
"|2019-03-01 10:30:00UTC |/home.html |12347 |",
"|2019-03-01 11:00:00UTC |/contact.html |12347 |",
"|2019-03-02 11:00:00UTC |/contact.html |12348 |"]
1.statistics page views and visitors
const pageDict = filtered.reduce((prev, cur) => {
// remove first `|` and last `|`
const record = cur.replace(/(^\|)|(\|$)/g, '');
const [time, url, userId] = record.split('|').map((v) => v.trim());
if (url in prev) {
prev[url].pageViews++;
prev[url].visitors.add(userId);
} else {
// if url not in prev, init
prev[url] = {
pageViews: 1,
visitors: new Set([userId]),
}
}
return prev;
}, {});
2.format data
const result = Object.entries(pageDict).map(([key, value]) => {
const { pageViews, visitors } = value;
return {
url: key,
pageViews: pageViews,
visitors: visitors.size,
}
})
console.log(result);
print result is:
[ { url: '/contact.html', pageViews: 5, visitors: 4 }, { url: '/home.html', pageViews: 1, visitors: 1 }]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.