How to combine common data in JSON object of Map()? - javascript

I have some JSON Data Like This:
{
"+2555970315763":{
"uid": "u9weKk62GvXu4Yf66HM2TFXDL5S2",
"phoneNumber": "+2555970315763",
"lastTime": "Mon, 14 Feb 2022 09:40:32 GMT"
},
"+2555970605736":{
"uid": "n3qGtqMWqVXGyZMSFz7HqwtfTDB3",
"phoneNumber": "+2555970605736",
"lastTime": "Mon, 14 Feb 2022 05:32:53 GMT"
},
"+2555973055799":{
"uid": "hGHq2TLCkeWsCWOZ0KdSI6mKbvp2",
"phoneNumber": "+2555973055799",
"lastTime": "Mon, 21 Feb 2022 05:25:46 GMT",
"usage": [
{
"firstTime": "18:04:34",
"count": 1,
"date": "2022-02-19"
},
{
"firstTime": "14:53:08",
"count": 6,
"date": "2022-02-21"
},
{
"count": 4,
"date": "2022-02-22",
"firstTime": "12:53:56"
},
{
"date": "2022-02-25",
"count": 4,
"firstTime": "12:12:03"
},
{
"firstTime": "12:35:04",
"date": "2022-02-26",
"count": 34
},
{
"count": 31,
"firstTime": "11:32:03",
"date": "2022-02-27"
}
]
},
"+2555974235764":{
"uid": "uUWJvN5XVwWGfNiC6UuwlmVVTO73",
"phoneNumber": "+2555974235764",
"lastTime": "Wed, 16 Feb 2022 06:04:54 GMT",
"usage": [
{
"count": 2,
"date": "2022-02-16",
"firstTime": "12:15:38"
},
{
"date": "2022-02-17",
"firstTime": "11:45:19",
"count": 43
},
{
"count": 148,
"firstTime": "11:33:53",
"date": "2022-02-19"
},
{
"count": 127,
"firstTime": "11:42:46",
"date": "2022-02-20",
"dow": "Sunday"
},
{
"firstTime": "12:18:28",
"count": 42,
"date": "2022-02-22",
}
]
},
"+2555979295712":{
"uid": "Cx63RRHQYpMMwfAbi0ebqledk5G3",
"phoneNumber": "+2555979295712",
"lastTime": "Tue, 01 Mar 2022 13:18:23 GMT",
},
"+2555970875726":{
"uid": "I5I3SFgZT3MAxomDHrPGq17OMcO2",
"phoneNumber": "+2555970875726",
"lastTime": "Tue, 01 Mar 2022 15:43:43 GMT",
},
"+2555970125770":{
"uid": "y9IcP0S6uHcOjPk0deXbuXZC4VA3",
"phoneNumber": "+2555970125770",
"lastTime": "Tue, 25 Jan 2022 09:38:27 GMT",
},
"+2555970335754":{
"uid": "gS2RkZdBlHZNOIYQUXB1iPfOkQ33",
"phoneNumber": "+2555970335754",
"lastTime": "Fri, 18 Feb 2022 07:40:32 GMT",
},
"+2555974475787":{
"uid": "QfSNsAMob8SXYWFB8TmgC0WMAXY2",
"phoneNumber": "+2555974475787",
"lastTime": "Fri, 11 Feb 2022 08:44:47 GMT",
},
"+2555974725740":{
"uid": "9y4unCW5PHRA0AjcVZdHFXh9thy1",
"phoneNumber": "+2555974725740",
"lastTime": "Mon, 21 Feb 2022 13:57:27 GMT",
}
}
I want to merge some of the phonenumber data like +2555973055799 and +2555974235764, I the for example: they both have objects with date:2022-02-19 so, the resultant object after merging should be like:
{
"firstTime": "11:33:53",
"count": 149,
"date": "2022-02-19"
},
count should be sum of both objects from phonenumbers ad firstTime should be time which is first. and uid, phone number should be concatinated, lastTime should be which is greater of two times?
The remaining phonenumbers data should be unchanged, only these two objects data should be merged,
How should I do that?
can anyone please help with this?

I am not sure if i understand your question correctly, but let's give it a try.
So, you would like to merge datas according to the date of usage. If 2 or more json objects was used on the same date, then you would like to to see the date, count and first time of use of these datas?
EDIT:
So, i created a prototype.
Maybe it is a little bit complicated solution, but i think it is good for a start.
I separated every object with usage data, then i looked for date duplicates, i stored both uid and the same date. Then i looked up for the count's and compared the firstTime datas and everything stored in the result variable.
Check console log for result.
var result = [] // we will store the result here
var dataWithUsage = [];
for (var i in obj) // iterate thru every data
if (obj[i].usage) // if data has usage property
{
dataWithUsage.push(obj[i]) // separate it from the main data structure
}
// console.log(dataWithUsage)
var usages = [] // we will collect every usage here
dataWithUsage.forEach(data => {
// console.log(data.usage, data.uid)
data.usage.forEach(element => {
usages.push({ date: element.date, uid: data.uid })
});
});
// console.log(usages)
// we will compare every usage and we try to do it only once
for (let i = 0; i < usages.length; i++) {
for (let j = i + 1; j < usages.length; j++) {
// console.log(usages[i], "vs" , usages[j])
if (usages[i].date == usages[j].date) {
result.push({ date: usages[i].date, uid1: usages[i].uid, uid2: usages[j].uid })
}
}
}
// at this point in the results we have our uid's with dates. Now we can do the data merge
result.forEach(element => {
var uid1Index = dataWithUsage.findIndex(object => object.uid == element.uid1)
var uid2Index = dataWithUsage.findIndex(object => object.uid == element.uid2) // we got the 2 objects for data merge
var count = 0
var firstTime
let usageIndexofuid1 = dataWithUsage[uid1Index].usage.findIndex(elem => elem.date == element.date)
let usageIndexofuid2 = dataWithUsage[uid2Index].usage.findIndex(elem => elem.date == element.date)
count = dataWithUsage[uid1Index].usage[usageIndexofuid1].count + dataWithUsage[uid2Index].usage[usageIndexofuid2].count
// console.log(dataWithUsage[uid1Index].usage[usageIndexofuid1].firstTime, dataWithUsage[uid2Index].usage[usageIndexofuid2].firstTime)
// console.log(dataWithUsage[uid1Index].usage[usageIndexofuid1].firstTime > dataWithUsage[uid2Index].usage[usageIndexofuid2].firstTime)
firstTime = ((dataWithUsage[uid1Index].usage[usageIndexofuid1].firstTime < dataWithUsage[uid2Index].usage[usageIndexofuid2].firstTime) ? dataWithUsage[uid1Index].usage[usageIndexofuid1].firstTime : dataWithUsage[uid2Index].usage[usageIndexofuid2].firstTime)
// console.log(firstTime,"fistTime")
// console.log(count,"count")
element.count = count
element.firstTime = firstTime
});
console.log("result")
console.log(result)
https://jsfiddle.net/peaq6cb3/

Related

Nested array within nested object

I had an object whose structure is
const data = {
"message": "fetch responces successfully",
"responce": [
{
"created_AT": "Mon, 03 Jan 2022 17:39:24 GMT",
"created_BY": "avinash",
"dateTime": "Mon, 03 Jan 2022 17:39:24 GMT",
"deleted_BY": "",
"flag": 0,
"project_ID": "infobot1234",
"responce": {
"uttence_test_heading": [
{
"buttons": [
{
"payload": "/my_localities",
"title": "savings"
},
{
"payload": "/my_localities12333qqqwq",
"title": "current"
},
{
"payload": "/fruits",
"title": "platinum"
}
]
},
{
"title": "Test Heading"
}
]
},
"responce_ID": "6bbb20d6-7f71-408a-a78a-bab39a30016f",
"responce_name": "uttence_test_heading",
"updated_BY": "",
"user_ID": "av1234"
},
{
"created_AT": "Tue, 04 Jan 2022 17:49:36 GMT",
"created_BY": "avinash",
"dateTime": "Tue, 04 Jan 2022 17:49:36 GMT",
"deleted_BY": "",
"flag": 0,
"project_ID": "infobot1234",
"responce": {
"utter_content": [
{
"text": "text_title for buttonqwqwq"
}
]
},
"responce_ID": "81d699ee-3e78-4356-b703-af095d91e36b",
"responce_name": "utter_txt1234",
"updated_BY": "",
"user_ID": "av1234"
},
{
"created_AT": "Thu, 13 Jan 2022 18:06:39 GMT",
"created_BY": "avinash",
"dateTime": "Thu, 13 Jan 2022 18:06:39 GMT",
"deleted_BY": "",
"flag": 0,
"project_ID": "infobot1234",
"responce": {
"uttence_text_heading": [
{
"buttons": [
{
"payload": "/my_localities",
"title": "savings"
},
{
"payload": "/my_localities12333qqqwq",
"title": "current"
},
{
"payload": "/test",
"title": "premium"
}
]
},
{
"title": "Text Heading"
}
]
},
"responce_ID": "bb6b0005-bbd4-49a1-8b25-58e0768800a1",
"responce_name": "uttence_text_heading",
"updated_BY": "",
"user_ID": "av1234"
},
{
"created_AT": "Thu, 13 Jan 2022 20:13:54 GMT",
"created_BY": "avinash",
"dateTime": "Thu, 13 Jan 2022 20:13:54 GMT",
"deleted_BY": "",
"flag": 0,
"project_ID": "infobot1234",
"responce": {
"uttence_heading_test": [
{
"buttons": [
{
"payload": "/my_localities",
"title": "savings"
},
{
"payload": "/fruits",
"title": "current"
},
{
"payload": "/undefined",
"title": "premium"
}
]
},
{
"title": "heading test"
}
]
},
"responce_ID": "7aeb2a42-a5f8-464d-832d-47cee4cfdb38",
"responce_name": "uttence_heading_test",
"updated_BY": "",
"user_ID": "av1234"
}
],
"status_code": 0
}
I was able to extract below array of objects by using data.responce.map(responce => responce.responce)
[{
uttence_test_heading: [{
buttons: [{
payload: "/my_localities",
title: "savings"
}, {
payload: "/my_localities12333qqqwq",
title: "current"
}, {
payload: "/fruits",
title: "platinum"
}]
}, {
title: "Test Heading"
}]
}, {
utter_content: [{
text: "text_title for buttonqwqwq"
}]
}, {
uttence_text_heading: [{
buttons: [{
payload: "/my_localities",
title: "savings"
}, {
payload: "/my_localities12333qqqwq",
title: "current"
}, {
payload: "/test",
title: "premium"
}]
}, {
title: "Text Heading"
}]
}, {
uttence_heading_test: [{
buttons: [{
payload: "/my_localities",
title: "savings"
}, {
payload: "/fruits",
title: "current"
}, {
payload: "/undefined",
title: "premium"
}]
}, {
title: "heading test"
}]
}]
Now I want to construct an array of objects whose structure is something like below
This is my expected result, but I am stuck since the uttence_name is a key and it is different for each object so could someone please guide me through how can I acheive my expected result. Please Help !
[{uttence_name: ' uttence_test_heading',buttons: ['savings','current','platinum'],text: '',responce_ID:'6bbb20d6-7f71-408a-a78a-bab39a30016f'},
{uttence_name: 'utter_content',buttons: '',text: 'text_title for buttonqwqwq',responce_ID:'81d699ee-3e78-4356-b703-af095d91e36b'},
{uttence_name:'uttence_text_heading',buttons:['savings','current','premium'],text: '',responce_ID:'bb6b0005-bbd4-49a1-8b25-58e0768800a1'}]
You can chain a second map and obtain the desired result. But my answer assumes that the arrays only have a single item in them.
Also, I didn't quite understand what you wanted to do with the buttons so I've kept them as an array.
You can run the snippet below to see if you're getting the desired output.
const data={message:"fetch responces successfully",responce:[{created_AT:"Mon, 03 Jan 2022 17:39:24 GMT",created_BY:"avinash",dateTime:"Mon, 03 Jan 2022 17:39:24 GMT",deleted_BY:"",flag:0,project_ID:"infobot1234",responce:{uttence_test_heading:[{buttons:[{payload:"/my_localities",title:"savings",},{payload:"/my_localities12333qqqwq",title:"current",},{payload:"/fruits",title:"platinum",},],},{title:"Test Heading",},],},responce_ID:"6bbb20d6-7f71-408a-a78a-bab39a30016f",responce_name:"uttence_test_heading",updated_BY:"",user_ID:"av1234",},{created_AT:"Tue, 04 Jan 2022 17:49:36 GMT",created_BY:"avinash",dateTime:"Tue, 04 Jan 2022 17:49:36 GMT",deleted_BY:"",flag:0,project_ID:"infobot1234",responce:{utter_content:[{text:"text_title for buttonqwqwq",},],},responce_ID:"81d699ee-3e78-4356-b703-af095d91e36b",responce_name:"utter_txt1234",updated_BY:"",user_ID:"av1234",},{created_AT:"Thu, 13 Jan 2022 18:06:39 GMT",created_BY:"avinash",dateTime:"Thu, 13 Jan 2022 18:06:39 GMT",deleted_BY:"",flag:0,project_ID:"infobot1234",responce:{uttence_text_heading:[{buttons:[{payload:"/my_localities",title:"savings",},{payload:"/my_localities12333qqqwq",title:"current",},{payload:"/test",title:"premium",},],},{title:"Text Heading",},],},responce_ID:"bb6b0005-bbd4-49a1-8b25-58e0768800a1",responce_name:"uttence_text_heading",updated_BY:"",user_ID:"av1234",},{created_AT:"Thu, 13 Jan 2022 20:13:54 GMT",created_BY:"avinash",dateTime:"Thu, 13 Jan 2022 20:13:54 GMT",deleted_BY:"",flag:0,project_ID:"infobot1234",responce:{uttence_heading_test:[{buttons:[{payload:"/my_localities",title:"savings",},{payload:"/fruits",title:"current",},{payload:"/undefined",title:"premium",},],},{title:"heading test",},],},responce_ID:"7aeb2a42-a5f8-464d-832d-47cee4cfdb38",responce_name:"uttence_heading_test",updated_BY:"",user_ID:"av1234",},],status_code:0,}
const result = data.responce
.map((res) => ({...res.responce, responce_ID: res.responce_ID }))
.map((obj) => ({
utterance_name: Object.keys(obj)[0],
text: Object.values(obj)[0][0].text || "",
buttons: Object.values(obj)[0][0].buttons?.map((btn) => btn.title) || "",
responce_ID: obj.responce_ID
}));
console.log(result);
Here is the required result based upon the data you have given. In the code, the best case scenario is, it checks whether you have object containing text or not and then adds the data accordingly. It also has response_ID
const data={message:"fetch responces successfully",responce:[{created_AT:"Mon, 03 Jan 2022 17:39:24 GMT",created_BY:"avinash",dateTime:"Mon, 03 Jan 2022 17:39:24 GMT",deleted_BY:"",flag:0,project_ID:"infobot1234",responce:{uttence_test_heading:[{buttons:[{payload:"/my_localities",title:"savings",},{payload:"/my_localities12333qqqwq",title:"current",},{payload:"/fruits",title:"platinum",},],},{title:"Test Heading",},],},responce_ID:"6bbb20d6-7f71-408a-a78a-bab39a30016f",responce_name:"uttence_test_heading",updated_BY:"",user_ID:"av1234",},{created_AT:"Tue, 04 Jan 2022 17:49:36 GMT",created_BY:"avinash",dateTime:"Tue, 04 Jan 2022 17:49:36 GMT",deleted_BY:"",flag:0,project_ID:"infobot1234",responce:{utter_content:[{text:"text_title for buttonqwqwq",},],},responce_ID:"81d699ee-3e78-4356-b703-af095d91e36b",responce_name:"utter_txt1234",updated_BY:"",user_ID:"av1234",},{created_AT:"Thu, 13 Jan 2022 18:06:39 GMT",created_BY:"avinash",dateTime:"Thu, 13 Jan 2022 18:06:39 GMT",deleted_BY:"",flag:0,project_ID:"infobot1234",responce:{uttence_text_heading:[{buttons:[{payload:"/my_localities",title:"savings",},{payload:"/my_localities12333qqqwq",title:"current",},{payload:"/test",title:"premium",},],},{title:"Text Heading",},],},responce_ID:"bb6b0005-bbd4-49a1-8b25-58e0768800a1",responce_name:"uttence_text_heading",updated_BY:"",user_ID:"av1234",},{created_AT:"Thu, 13 Jan 2022 20:13:54 GMT",created_BY:"avinash",dateTime:"Thu, 13 Jan 2022 20:13:54 GMT",deleted_BY:"",flag:0,project_ID:"infobot1234",responce:{uttence_heading_test:[{buttons:[{payload:"/my_localities",title:"savings",},{payload:"/fruits",title:"current",},{payload:"/undefined",title:"premium",},],},{title:"heading test",},],},responce_ID:"7aeb2a42-a5f8-464d-832d-47cee4cfdb38",responce_name:"uttence_heading_test",updated_BY:"",user_ID:"av1234",},],status_code:0,};
let newObject = [];
data.responce.forEach((item) => {
// We will get each item here now
// Assuming object of item.responce will come always
const objectName = Object.keys(item.responce)[0];
const dataToPush = {
'responce_ID': item.responce_ID,
'uttence_name': objectName,
'buttons': item.responce[objectName][0].buttons ? item.responce[objectName][0].buttons.map(data => data.title) : '',
'text': item.responce[objectName].find(data => data.hasOwnProperty('text')) ? item.responce[objectName].map(value => value.text)[0] : ''
};
// Finally adding the item to the array to give the final output
newObject.push(dataToPush);
});
console.log(newObject);

How do I get the total number of occurrence for each array in an object?

i currently have this object in React and i can't seem to get the output i want, i am not sure if i have structured the object properly. The data are retrieved using Firestore. I have stored the results in to this summary array and tried working on it
const summary = [
{
data: [
{
date: "Sep 21 2021",
prodID: "005",
},
],
},
{
data: [
{
date: "Sep 21 2021",
prodID: "002",
},
{
date: "Sep 21 2021",
prodID: "002",
},
],
},
{
data: [
{
date: "Sep 21 2021",
prodID: "004",
},
{
date: "Sep 21 2021",
prodID: "004",
},
{
date: "Sep 21 2021",
prodID: "004",
},
{
date: "Sep 19 2021",
prodID: "004",
},
{
date: "Sep 19 2021",
prodID: "004",
},
],
}, ];
Is it even possible to get this output.. I have been trying for countless of hours now.. how do i code it such that i will get a result like this?
[
{
"count": 1,
"date": "Sep 21 2021",
"prodID": "005"
},
{
"count": 2,
"date": "Sep 21 2021",
"prodID": "002"
},
{
"count": 3,
"date": "Sep 21 2021",
"prodID": "004"
},
{
"count": 2,
"date": "Sep 19 2019",
"prodID": "004"
}
]
This is the latest logic that i've tried
firebase
.firestore()
.collection("batch")
.doc(ctx.currentUser.companyName)
.collection("products")
.get()
.then((snapshot) => {
let arr = [];
snapshot.forEach((doc) => {
const dt = doc.data().prodID;
if (!arr[dt]) {
arr[dt] = 1;
} else {
arr[dt] += 1;
}
});
for (const t in arr) {
firebase
.firestore()
.collection("batch")
.doc(ctx.currentUser.companyName)
.collection("products")
.where("prodID", "==", t)
.orderBy("dateAdded", "desc")
.get()
.then((snapshot) => {
let arr2 = [];
let c = 0;
snapshot.forEach((doc) => {
const dt = getDate(doc.data().dateAdded["seconds"]);
if (!arr2[c]) {
arr2[c] = { count: 1, date: dt, prodID: t };
} else {
console.log("in");
if (arr2.prodID === t) {
for (const d in arr2) {
if (arr2[d].count) {
arr2[d].count++;
}
}
}
}
c++;
});
let v = {};
v["data"] = arr2;
addSummary(v);
});
}
});
This is the result i get after executing
for (let j = 0; j < summary.length; j++) {
for (let k = 0; k < summary[j].data.length; k++) {
console.log(summary[j].data[k]);
}
}
console result
Iterate over data and for each unique date (new Set(d.data.map(prod => prod.date))) add to result the count (d.data.filter(prod => prod.date === date).length)
const summary = [{
data: [{
date: "Sep 21 2021",
prodID: "005",
}, ],
},
{
data: [{
date: "Sep 21 2021",
prodID: "002",
},
{
date: "Sep 21 2021",
prodID: "002",
},
],
},
{
data: [{
date: "Sep 21 2021",
prodID: "004",
},
{
date: "Sep 21 2021",
prodID: "004",
},
{
date: "Sep 21 2021",
prodID: "004",
},
{
date: "Sep 19 2021",
prodID: "004",
},
{
date: "Sep 19 2021",
prodID: "004",
},
],
},
];
const result = []
summary.forEach(d => {
let dates = new Set(d.data.map(prod => prod.date))
dates.forEach(date => {
result.push({
date: date,
prodId: d.data[0].prodID,
count: d.data.filter(prod => prod.date === date).length
})
})
})
console.log(result)
Assuming summary is equal to snapshot your code should/could look like:
firebase
.firestore()
.collection("batch")
.doc(ctx.currentUser.companyName)
.collection("products")
.get()
.then((snapshot) => {
const result = []
snapshot.forEach(doc => {
let dates = new Set(doc.data.map(prod => prod.date))
dates.forEach(date => {
result.push({
date: date,
prodId: doc.data[0].prodID,
count: doc.data.filter(prod => prod.date === date).length
})
})
})
console.log(result)
})

What's the best way to group a JSON object by a certain value?

I want to be able to display data in an React application like so:
Today
- Batman entered the watchtower at 10:30am
- Batman entered the watchtower at 10:15am
- Wonder Woman entered the watchtower at 10:00am
Yesterday
- Flash entered the watchtower at 10:30am
- Green Lantern entered the watchtower at 10:15am
- Cyborg entered the watchtower at 10:00am
9th August 2018
- Aquaman entered the watchtower at 10:30am
The data being sent to me is an JSON Array of objects:
[{
"name": "Batman",
"secret_identity": "Bruce Wayne",
"timestamp": "1533983400" // Epoch timestamp equating to 11th August 2018 at 10:30am
},
{
"name": "Superman",
"secret_identity": "Clark Kent",
"timestamp": "1533982500" // Epoch timestamp equating to 11th August 2018 at 10:15am
},
{
"name": "Wonder Woman",
"secret_identity": "Diana Prince",
"timestamp": "1533981600" // Epoch timestamp equating to 11th August 2018 at 10:00am
},
{
"name": "Flash",
"secret_identity": "Wally West",
"timestamp": "1533897000" // Epoch timestamp equating to 10th August 2018 at 10:30am
},
{
"name": "Green Lantern",
"secret_identity": "Hal Jordan",
"timestamp": "1533896100" // Epoch timestamp equating to 10th August 2018 at 10:15am
},
{
"name": "Cyborg",
"secret_identity": "Victor Stone",
"timestamp": "1533895800" // Epoch timestamp equating to 10th August 2018 at 10:00am
},
{
"name": "Aquaman",
"secret_identity": "Arthur Curry",
"timestamp": "1533810600" // Epoch timestamp equating to 9th August 2018 at 10:30am
}]
I am not sure what's the best way to use this JSON Array to render the data in the way that I need. I thought I may need to process the data further in a new object like below but am not sure the best way to do so.
[{
"11-August-2018" : [{
"name": "Batman",
"secret_identity": "Bruce Wayne",
"timestamp": "1533983400" // 11th August 2018 at 10:30am
},
{
"name": "Superman",
"secret_identity": "Clark Kent",
"timestamp": "1533982500" // 11th August 2018 at 10:15am
},
{
"name": "Wonder Woman",
"secret_identity": "Diana Prince",
"timestamp": "1533981600" // 11th August 2018 at 10:00am
}],
"10-August-2018" : [{
"name": "Flash",
"secret_identity": "Wally West",
"timestamp": "1533897000" // 10th August 2018 at 10:30am
},
{
"name": "Green Lantern",
"secret_identity": "Hal Jordan",
"timestamp": "1533896100" // 10th August 2018 at 10:15am
},
{
"name": "Cyborg",
"secret_identity": "Victor Stone",
"timestamp": "1533895800" // 10th August 2018 at 10:00am
}],
"09-August-2018" : [{
"name": "Aquaman",
"secret_identity": "Arthur Curry",
"timestamp": "1533810600" // 9th August 2018 at 10:30am
}]
}]
Sorting, mapping, reducing. Gotta love es2018
(d => {
// a few utility methods
const dateFromEpoch = epochStr => new Date(new Date(0).setUTCSeconds(+epochStr));
const padLeft = n => `${n}`.padStart(2, "0");
const removeTime = dateTime => new Date(dateTime.toISOString().split("T")[0]);
const getDateLabel = dateTime => {
const now = removeTime(new Date());
const plainDate = removeTime(dateTime);
const dayDiff = Math.abs(Math.round(((plainDate - now) / 3600000) / 24));
return dayDiff < 1 ?
"Today" :
dayDiff === 1 ?
"Yesterday" :
`${dayDiff} Days ago`;
};
const heroicData = getHeroicData()
.sort((a, b) => +a.timestamp < +b.timestamp) // sort descending
.reduce(heroicReducer, {}); // create reshuffled object
// the heroic entry points
d.querySelector("#raw").textContent = JSON.stringify(heroicData, null, " ");
// create html output using a reducer
d.querySelector("#result").innerHTML = Object.keys(heroicData)
.reduce((reduced, day) =>
reduced.concat(`
<b>${day}</b>
<ul>
${heroicData[day].map(visit => `<li>${visit}</li>`).join("")}
</ul>`), [])
.join("");
function heroicReducer(reduced, heroicVisit) {
const dateTime = dateFromEpoch(heroicVisit.timestamp);
const reportKey = getDateLabel(dateTime);
const reportString = `<heroe>${
heroicVisit.name}</heroe> entered the watchtower at ${
padLeft(dateTime.getHours())}:${
padLeft(dateTime.getMinutes())}`;
if (reduced[reportKey]) {
reduced[reportKey].push(reportString)
} else {
reduced[reportKey] = [reportString];
}
return reduced;
}
function getHeroicData() {
return [{
"name": "Batman",
"secret_identity": "Bruce Wayne",
"timestamp": "1533983400"
},
{
"name": "Superman",
"secret_identity": "Clark Kent",
"timestamp": "1533982500"
},
{
"name": "Wonder Woman",
"secret_identity": "Diana Prince",
"timestamp": "1533981600"
},
{
"name": "Flash",
"secret_identity": "Wally West",
"timestamp": "1533897000"
},
{
"name": "Green Lantern",
"secret_identity": "Hal Jordan",
"timestamp": "1533896100"
},
{
"name": "Cyborg",
"secret_identity": "Victor Stone",
"timestamp": "1533895800"
},
{
"name": "Aquaman",
"secret_identity": "Arthur Curry",
"timestamp": "1533810600"
}
];
}
})(document);
body {
font: normal 12px/15px verdana, arial;
margin: 3em;
}
heroe {
color: red;
font-style: italic;
}
<pre id="raw"></pre>
<h3>**Reduced to output</h3>
<div id="result"></div>
You can group data with reduce function for example, also you can format date object by yourself or if you need some complex formatting in future you can use moment.js library(render "today", "yesterday", "th", "rd" etc). So I don't map month names and used just UTC in my example:
let data = [{
"name": "Batman",
"secret_identity": "Bruce Wayne",
"timestamp": "1533983400" // Epoch timestamp equating to 11th August 2018 at 10:30am
},
{
"name": "Superman",
"secret_identity": "Clark Kent",
"timestamp": "1533982500" // Epoch timestamp equating to 11th August 2018 at 10:15am
},
{
"name": "Wonder Woman",
"secret_identity": "Diana Prince",
"timestamp": "1533981600" // Epoch timestamp equating to 11th August 2018 at 10:00am
},
{
"name": "Flash",
"secret_identity": "Wally West",
"timestamp": "1533897000" // Epoch timestamp equating to 10th August 2018 at 10:30am
},
{
"name": "Green Lantern",
"secret_identity": "Hal Jordan",
"timestamp": "1533896100" // Epoch timestamp equating to 10th August 2018 at 10:15am
},
{
"name": "Cyborg",
"secret_identity": "Victor Stone",
"timestamp": "1533895800" // Epoch timestamp equating to 10th August 2018 at 10:00am
},
{
"name": "Aquaman",
"secret_identity": "Arthur Curry",
"timestamp": "1533810600" // Epoch timestamp equating to 9th August 2018 at 10:30am
}]
let result = data.reduce((acc, item) => {
let date = new Date(item.timestamp*1000);
let key = `${date.getUTCDate()}-${date.getUTCMonth()+1}-${date.getUTCFullYear()}`;
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(item);
return acc;
}, {})
console.log(result)
There are two smaller problems that you are trying to solve here:
Mapping epoch to date,
Grouping events by date
I'll use utility libraryramda to simplify the answer, but you could implement your own groupBy function if you wanted to.
Possible solution:
const epochToDate = epoch => {
const date = new Date(epoch)
return `${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()}`
}
const groupedJson = R.groupBy(
event => epochToDate(parseInt(event.timestamp, 10)),
rawJson
)
You can play with it in ramda repl.
u have to import the json file to your react application like this
import data from './data.json'
this.data = data
and just work with it like any other object
outJSON= [ {team: "TeamA",name: "Ahmed",field3:"val3"}, {team: "TeamB",name: "Ahmed",field3:"val43"}, {team: "TeamA",name: "Ahmed",field3:"val55"} ]
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
var groubedByTeam=groupBy(outJSON, 'team')
console.log(groubedByTeam);

How can I get data of last week or last month in JSON data?

Say, I have a JSON data
[
{
"transaction": "34",
"date": "Mar 12 2016 10:00:00 AM"
}, {
"transaction": "21",
"date": "Mar 12 2016 10:00:00 AM"
}, {
"transaction": "40",
"date": "Mar 13 2016 10:00:00 AM"
}, {
"transaction": "40",
"date": "Mar 14 2016 10:00:00 AM"
}
]
There may be several transactions in one day. How can I get the most recent one week's or month's transaction records from this JSON data?
Checkout below
Data seems not valid, i changed it from Object to Array
I added code for Last one month Data,Last One week
var data = [{
"transaction": "34",
"date": "Apr 12 2017 10:00:00 AM"
}, {
"transaction": "21",
"date": "Apr 12 2017 10:00:00 AM"
}, {
"transaction": "40",
"date": "Mar 15 2016 10:00:00 AM"
}, {
"transaction": "50",
"date": "Jan 13 2017 10:00:00 AM"
}, {
"transaction": "40",
"date": "Mar 13 2017 10:00:00 AM"
}, {
"transaction": "40",
"date": "Mar 14 2016 10:00:00 AM"
}];
//It will return dates diff in no. if months
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
//It will gets the last month date
function getLastMonth(){
var x = new Date();
x.setDate(1);
x.setMonth(x.getMonth()-1);
return x;
}
var prevMonthDate = getLastMonth();
var lastMonthData = data.filter(function(v){
return monthDiff(new Date(v.date),prevMonthDate) < 1;
});
//This is the data for last one Month
console.log(lastMonthData);
//It will return dates diff in no. if Weeks
function weekDiff(d1,d2){
var dif = Math.round(d1-d2);
return Math.ceil(dif/1000/60/60/24/7);
}
//It will gets the last week date
function getLastWeek(){
var today = new Date();
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek ;
}
var prevWeekDate = getLastWeek();
var lastWeekData = data.filter(function(v){
return weekDiff(new Date(v.date),prevWeekDate) == 1;
});
//This is the data for last one Week
console.log(lastWeekData);
Working example in Fiddle

Adding elements to array inside for.. in

I'm trying to make a 2 dimensional array with a json data. The first array is made within a for in loop and is pushed to the top-level array after. I tried to print the array and I got same value for each elements which is the last data from the json.
json:
[
{
"startYear": 2014,
"startMonth": 6,
"startDay": 31,
"endYear": 2014,
"endMonth": 7,
"endDay": 29,
"selectedDate": "2014_7_8",
"departureStation": "Manila",
"arrivalStation": "Boracay (Caticlan)",
"departureStationCode": "(MNL)",
"arrivalStationCode": "(MPH)",
"departureLabel": "DEPARTURE",
"arrivalLabel": "RETURN",
"dateMarketHash": {
"date_0_2014_6_31": {
"containerId": "date_0_2014_6_31",
"fromLabel": "From",
"currency": "PHP",
"price": null,
"formattedDate": "Thu, Jul 31, 2014", //data to get
"year": "2014",
"month": "6",
"day": "31",
"points": null,
"pointsSuffix": "",
"pointsLabelAppend": ""
},
"date_0_2014_7_1": {
"containerId": "date_0_2014_7_1",
"fromLabel": "From",
"currency": "PHP",
"price": 1929,
"formattedDate": "Fri, Aug 01, 2014", //data to get
"year": "2014",
"month": "7",
"day": "1",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
}
}
},
{
"startYear": 2014,
"startMonth": 7,
"startDay": 24,
"endYear": 2014,
"endMonth": 8,
"endDay": 23,
"selectedDate": "2014_8_8",
"departureStation": "Boracay (Caticlan)",
"arrivalStation": "Manila",
"departureStationCode": "(MPH)",
"arrivalStationCode": "(MNL)",
"departureLabel": "DEPARTURE",
"arrivalLabel": "RETURN",
"dateMarketHash": {
"date_1_2014_7_24": {
"containerId": "date_1_2014_7_24",
"fromLabel": "From",
"currency": "PHP",
"price": 3079,
"formattedDate": "Sun, Aug 24, 2014",
"year": "2014",
"month": "7",
"day": "24",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
},
"date_1_2014_7_25": {
"containerId": "date_1_2014_7_25",
"fromLabel": "From",
"currency": "PHP",
"price": 3079,
"formattedDate": "Mon, Aug 25, 2014",
"year": "2014",
"month": "7",
"day": "25",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
}
}
}
]
code:
var current = json[0].dateMarketHash;
var top = [];
var array = [];
for(var key in current){
top[0] = current[key].formattedDate;
top[1] = current[key].currency;
top[2] = current[key].price;
array.push(top);
}
document.write(array[0][0]); //prints "Fri, Aug 01, 2014" instead of "Thu, Jul 31, 2014"
document.write(array[1][0]); //prints "Fri, Aug 01, 2014"
It is because you initialize top outside the loop scope and that makes top[0] overwrite all references to the top array, which are being held in array
Put the top declaration inside the loop and see the difference
var current = json[0].dateMarketHash;
var array = [];
for(var key in current){
var top = [];
top[0] = current[key].formattedDate;
top[1] = current[key].currency;
top[2] = current[key].price;
array[array.length] = top;
}
http://jsfiddle.net/sUpC8/
If you insist on top being outside the loop scope you can work-around this problem by cloning the top array
var current = json[0].dateMarketHash;
var array = [];
var top = [];
for(var key in current){
top[0] = current[key].formattedDate;
top[1] = current[key].currency;
top[2] = current[key].price;
array[array.length] = top.slice(0);
}
Place "var top=[]" inside the loop and change array.push(top) to array.unshift(top), unshift method always insert element to the index 0.

Categories