Compare JSON object array using Jquery - javascript

I have a selected list object like this {"0":"1","2":"1"},
I want to compare it with another array like the following
{
"0": {
"id": 1,
"salutation": "Dr.",
"firstname": "Kapil",
"lastname": "Dev",
"gender": "Male ",
"email": "kapil.dev#aggenome.com",
"phone": 1232423415,
"usertype": "student",
"institution": "AgriGenome Labs Pvt Ltd",
"department": "Lab",
"country": "India",
"conferenceitem": "2017 NGBT Conference ",
"conferenceitemid": "39",
"amount": 2800,
"actual_amount": "5000.00",
"currency": "INR",
"group": "Lead",
"accompany": "No",
"password": null,
"mailsend": "Yes"
},
"1": {
"id": 2,
"salutation": "Mr.",
"firstname": "Sunil",
"lastname": "Gavaskar",
"gender": "Male ",
"email": "sunil.gavaskar#aggenome.com",
"phone": 1232423415,
"usertype": "commercial",
"institution": "AgriGenome Labs Pvt Ltd",
"department": "Bio Info",
"country": "India",
"conferenceitem": "2017 NGBT Conference ",
"conferenceitemid": "31",
"amount": "3100.00",
"actual_amount": "10000.00",
"currency": "INR",
"group": "Yes",
"accompany": "No",
"password": null,
"mailsend": "Yes"
},
"2": {
"id": 3,
"salutation": "Mr.",
"firstname": "Anil",
"lastname": "Kumble",
"gender": "Male ",
"email": "anil.kumble#aggenome.com",
"phone": 1232423415,
"usertype": "student",
"institution": "AgriGenome Labs Pvt Ltd",
"department": "Support",
"country": "India",
"conferenceitem": "Accompanying Person",
"conferenceitemid": "5",
"amount": 1900,
"actual_amount": "5000.00",
"currency": "INR",
"group": "No",
"accompany": "Yes",
"password": null,
"mailsend": "No"
}
}
on the basis of the keys, means that only 0 & 2 are selected and I need to fetch data from the second object having key 0 & 2, (excluding 1 ), how can I do this? I am new to this area...

var obj = {"0":"1","2":"1"};
var newobj = {
"0": {
"id": 1,
"salutation": "Dr.",
"firstname": "Kapil",
"lastname": "Dev",
"gender": "Male ",
"email": "kapil.dev#aggenome.com",
"phone": 1232423415,
"usertype": "student",
"institution": "AgriGenome Labs Pvt Ltd",
"department": "Lab",
"country": "India",
"conferenceitem": "2017 NGBT Conference ",
"conferenceitemid": "39",
"amount": 2800,
"actual_amount": "5000.00",
"currency": "INR",
"group": "Lead",
"accompany": "No",
"password": null,
"mailsend": "Yes"
},
"1": {
"id": 2,
"salutation": "Mr.",
"firstname": "Sunil",
"lastname": "Gavaskar",
"gender": "Male ",
"email": "sunil.gavaskar#aggenome.com",
"phone": 1232423415,
"usertype": "commercial",
"institution": "AgriGenome Labs Pvt Ltd",
"department": "Bio Info",
"country": "India",
"conferenceitem": "2017 NGBT Conference ",
"conferenceitemid": "31",
"amount": "3100.00",
"actual_amount": "10000.00",
"currency": "INR",
"group": "Yes",
"accompany": "No",
"password": null,
"mailsend": "Yes"
},
"2": {
"id": 3,
"salutation": "Mr.",
"firstname": "Anil",
"lastname": "Kumble",
"gender": "Male ",
"email": "anil.kumble#aggenome.com",
"phone": 1232423415,
"usertype": "student",
"institution": "AgriGenome Labs Pvt Ltd",
"department": "Support",
"country": "India",
"conferenceitem": "Accompanying Person",
"conferenceitemid": "5",
"amount": 1900,
"actual_amount": "5000.00",
"currency": "INR",
"group": "No",
"accompany": "Yes",
"password": null,
"mailsend": "No"
}
}
var newArray = Object.keys(obj).map(item => {
return newobj[item]})
console.log(newArray)

Considering you only want to the object filtered out from your selection, you could use forEach on Object.keys of your selected object
var obj = {"0":"1","2":"1"};
var newobj = {
"0": {
"id": 1,
"salutation": "Dr.",
"firstname": "Kapil",
"lastname": "Dev",
"gender": "Male ",
"email": "kapil.dev#aggenome.com",
"phone": 1232423415,
"usertype": "student",
"institution": "AgriGenome Labs Pvt Ltd",
"department": "Lab",
"country": "India",
"conferenceitem": "2017 NGBT Conference ",
"conferenceitemid": "39",
"amount": 2800,
"actual_amount": "5000.00",
"currency": "INR",
"group": "Lead",
"accompany": "No",
"password": null,
"mailsend": "Yes"
},
"1": {
"id": 2,
"salutation": "Mr.",
"firstname": "Sunil",
"lastname": "Gavaskar",
"gender": "Male ",
"email": "sunil.gavaskar#aggenome.com",
"phone": 1232423415,
"usertype": "commercial",
"institution": "AgriGenome Labs Pvt Ltd",
"department": "Bio Info",
"country": "India",
"conferenceitem": "2017 NGBT Conference ",
"conferenceitemid": "31",
"amount": "3100.00",
"actual_amount": "10000.00",
"currency": "INR",
"group": "Yes",
"accompany": "No",
"password": null,
"mailsend": "Yes"
},
"2": {
"id": 3,
"salutation": "Mr.",
"firstname": "Anil",
"lastname": "Kumble",
"gender": "Male ",
"email": "anil.kumble#aggenome.com",
"phone": 1232423415,
"usertype": "student",
"institution": "AgriGenome Labs Pvt Ltd",
"department": "Support",
"country": "India",
"conferenceitem": "Accompanying Person",
"conferenceitemid": "5",
"amount": 1900,
"actual_amount": "5000.00",
"currency": "INR",
"group": "No",
"accompany": "Yes",
"password": null,
"mailsend": "No"
}
}
const result = {}
Object.keys(obj).forEach(key => {
result[key] = newobj[key]
})
console.log(result)

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
var flag = {"0":"1","2":"1"};
var data = {"0":{"id":1,"salutation":"Dr.","firstname":"Kapil","lastname":"Dev","gender":"Male ","email":"kapil.dev#aggenome.com","phone":1232423415,"usertype":"student","institution":"AgriGenome Labs Pvt Ltd","department":"Lab","country":"India","conferenceitem":"2017 NGBT Conference ","conferenceitemid":"39","amount":2800,"actual_amount":"5000.00","currency":"INR","group":"Lead","accompany":"No","password":null,"mailsend":"Yes"},"1":{"id":2,"salutation":"Mr.","firstname":"Sunil","lastname":"Gavaskar","gender":"Male ","email":"sunil.gavaskar#aggenome.com","phone":1232423415,"usertype":"commercial","institution":"AgriGenome Labs Pvt Ltd","department":"Bio Info","country":"India","conferenceitem":"2017 NGBT Conference ","conferenceitemid":"31","amount":"3100.00","actual_amount":"10000.00","currency":"INR","group":"Yes","accompany":"No","password":null,"mailsend":"Yes"},"2":{"id":3,"salutation":"Mr.","firstname":"Anil","lastname":"Kumble","gender":"Male ","email":"anil.kumble#aggenome.com","phone":1232423415,"usertype":"student","institution":"AgriGenome Labs Pvt Ltd","department":"Support","country":"India","conferenceitem":"Accompanying Person","conferenceitemid":"5","amount":1900,"actual_amount":"5000.00","currency":"INR","group":"No","accompany":"Yes","password":null,"mailsend":"No"}};
//loop the flag
$.each( flag, function(i,c){
//loop the data
$.each(data,function(di,dc){
if(i == di)
{
//data you want
console.log(dc)
}
});
});
</script>
</html>

Related

How to avoid overwriting of a JSON object in React?

I'm comparing two JSON and returning mismatched values from the second JSON with a key and storing them in a new JSON object. I'm using a loop for comparing two JSON objects. If there is more than one difference, it is overwritten by the previous object stored. Can you please tell me how to resolve it?
var finalOutputJson;
let jsonOutput1 = {},
jsonOutput2 = {};
for (let i of jsonData1) {
var d = jsonData2.filter(
(data) => data.Unique == i.Unique
);
if (d != []) {
let keys = Object.keys(i);
for (let j of keys) {
if (j == "Title") {
if (i[j] != d[0]["Name"].Title) {
jsonOutput1 = { [j]: d[0]["Name"].Title };
console.log(jsonOutput1);
}
} else if (i[j] != d[0][j]) {
jsonOutput2 = { [j]: d[0][j] };
console.log(jsonOutput2);
}
[![jsonOutput1][1]][1]
inputJsonData1 :-
[
{
"Title": "Ankit Singh1",
"Aadhar_x0020_Nuber": 999941057058,
"Age": 54,
"Gender": "M",
"Phone": 2810806979,
"Father_x0020_Name": "Mr. Choudhury",
"Email": "sschoudhury#dummyemail.com",
"City": "New Delhi",
"State": "New delhi"
},
{
"Title": "Munendra",
"Aadhar_x0020_Nuber": 999971658847,
"Age": 44,
"Gender": "M",
"Phone": 2314475929,
"Father_x0020_Name": "Mr. Agarwal",
"Email": "kma#mailserver.com",
"City": "Udaipur",
"State": "Rajasthan"
},
{
"Title": "Mayank Sharma3",
"Aadhar_x0020_Nuber": 999933119405,
"Age": 79,
"Gender": "F",
"Phone": 2837032088,
"Father_x0020_Name": "Mr. Bedi",
"Email": "bedi2020#mailserver.com",
"City": "Bareilly",
"State": "Uttar Pradesh"
},
{
"Title": "Shikhar Saxena5",
"Aadhar_x0020_Nuber": 999955183433,
"Age": 37,
"Gender": "M",
"Phone": 2821096353,
"Father_x0020_Name": "Mr. Pandey",
"Email": "rpandey#mailserver.com",
"City": "Mumbai",
"State": "Maharastra"
},
{
"Title": "Namita Rastogi",
"Aadhar_x0020_Nuber": 999990501894,
"Age": 40,
"Gender": "F",
"Phone": 2821096350,
"Father_x0020_Name": "Mr. Kapoor",
"Email": "anisha#gmail.com",
"City": "Bangalore",
"State": "Karnataka"
}
]
inputJsonData2:-
[
{
"odata.type": "SP.Data.Aadhar_x005f_DataListItem",
"odata.id": "1a8bda26-b339-4e95-a42e-cf8b15aa571c",
"odata.etag": "\"3\"",
"odata.editLink": "Web/Lists(guid'f57b8a37-9a12-48fa-ae4a-f2c360611fd2')/Items(1)",
"Name#odata.navigationLinkUrl": "Web/Lists(guid'f57b8a37-9a12-48fa-ae4a-f2c360611fd2')/Items(1)/Name",
"Name": {
"odata.type": "SP.Data.UserInfoItem",
"odata.id": "e0fc5839-8528-460f-9a97-735b3e676870",
"Title": "Ankit Singh"
},
"FileSystemObjectType": 0,
"Id": 1,
"ServerRedirectedEmbedUri": null,
"ServerRedirectedEmbedUrl": "",
"ID": 1,
"ContentTypeId": "0x0100CAEC71E55732C14BA36095D2FA8E6CA80037B4C7B1E7CFFA4D83E55D30CD77AC99",
"Title": null,
"Modified": "2022-06-07T09:31:14Z",
"Created": "2022-06-02T08:15:05Z",
"AuthorId": 1282,
"EditorId": 1282,
"OData__UIVersionString": "3.0",
"Attachments": false,
"GUID": "c27f786a-8599-400c-b284-f7bec308a861",
"ComplianceAssetId": null,
"Aadhar_x0020_Nuber": 999941057058,
"NameId": 1282,
"NameStringId": "1282",
"Age": 54,
"Gender": "M",
"Phone": 2810806979,
"Father_x0020_Name": "Mr. Choudhury",
"Email": "sschoudhury#dummyemail.com",
"City": "New Delhi",
"State": "New delhi"
},
{
"odata.type": "SP.Data.Aadhar_x005f_DataListItem",
"odata.id": "bbb3d19c-5fae-463b-993a-08e3665f4997",
"odata.etag": "\"2\"",
"odata.editLink": "Web/Lists(guid'f57b8a37-9a12-48fa-ae4a-f2c360611fd2')/Items(2)",
"Name#odata.navigationLinkUrl": "Web/Lists(guid'f57b8a37-9a12-48fa-ae4a-f2c360611fd2')/Items(2)/Name",
"Name": {
"odata.type": "SP.Data.UserInfoItem",
"odata.id": "f9f74da9-4aba-4cdc-8e4f-2985883c4602",
"Title": "Munendra"
},
"FileSystemObjectType": 0,
"Id": 2,
"ServerRedirectedEmbedUri": null,
"ServerRedirectedEmbedUrl": "",
"ID": 2,
"ContentTypeId": "0x0100CAEC71E55732C14BA36095D2FA8E6CA80037B4C7B1E7CFFA4D83E55D30CD77AC99",
"Title": null,
"Modified": "2022-06-16T06:40:16Z",
"Created": "2022-06-02T08:17:48Z",
"AuthorId": 1282,
"EditorId": 1282,
"OData__UIVersionString": "2.0",
"Attachments": false,
"GUID": "afb84bd6-0253-4bf8-a515-824b13ae1a4e",
"ComplianceAssetId": null,
"Aadhar_x0020_Nuber": 999971658847,
"NameId": 107,
"NameStringId": "107",
"Age": 44,
"Gender": "F",
"Phone": 2314475929,
"Father_x0020_Name": "Mr. Agarwal",
"Email": "kma#mailserver.com",
"City": "Udaipur",
"State": "Rajasthan"
},
{
"odata.type": "SP.Data.Aadhar_x005f_DataListItem",
"odata.id": "49217d7e-200c-496b-b728-bd5307bbe1db",
"odata.etag": "\"1\"",
"odata.editLink": "Web/Lists(guid'f57b8a37-9a12-48fa-ae4a-f2c360611fd2')/Items(3)",
"Name#odata.navigationLinkUrl": "Web/Lists(guid'f57b8a37-9a12-48fa-ae4a-f2c360611fd2')/Items(3)/Name",
"Name": {
"odata.type": "SP.Data.UserInfoItem",
"odata.id": "df5b1286-0009-48ba-a7bc-7b269a9ebcf7",
"Title": "Mayank Sharma3"
},
"FileSystemObjectType": 0,
"Id": 3,
"ServerRedirectedEmbedUri": null,
"ServerRedirectedEmbedUrl": "",
"ID": 3,
"ContentTypeId": "0x0100CAEC71E55732C14BA36095D2FA8E6CA80037B4C7B1E7CFFA4D83E55D30CD77AC99",
"Title": null,
"Modified": "2022-06-02T08:18:58Z",
"Created": "2022-06-02T08:18:58Z",
"AuthorId": 1282,
"EditorId": 1282,
"OData__UIVersionString": "1.0",
"Attachments": false,
"GUID": "e5ac3af3-e024-4703-b946-96cdc2ff3b5e",
"ComplianceAssetId": null,
"Aadhar_x0020_Nuber": 999933119405,
"NameId": 705,
"NameStringId": "705",
"Age": 79,
"Gender": "M",
"Phone": 2837032088,
"Father_x0020_Name": "Mr. Bedi",
"Email": "bedi2020#mailserver.com",
"City": "Bareilly",
"State": "Uttar Pradesh"
},
{
"odata.type": "SP.Data.Aadhar_x005f_DataListItem",
"odata.id": "e1f7ffaa-1bc7-4afa-bccb-18965f13c750",
"odata.etag": "\"1\"",
"odata.editLink": "Web/Lists(guid'f57b8a37-9a12-48fa-ae4a-f2c360611fd2')/Items(4)",
"Name#odata.navigationLinkUrl": "Web/Lists(guid'f57b8a37-9a12-48fa-ae4a-f2c360611fd2')/Items(4)/Name",
"Name": {
"odata.type": "SP.Data.UserInfoItem",
"odata.id": "5f9e7c49-9bde-4b66-90c8-12e156db60ce",
"Title": "Shikhar Saxena"
},
"FileSystemObjectType": 0,
"Id": 4,
"ServerRedirectedEmbedUri": null,
"ServerRedirectedEmbedUrl": "",
"ID": 4,
"ContentTypeId": "0x0100CAEC71E55732C14BA36095D2FA8E6CA80037B4C7B1E7CFFA4D83E55D30CD77AC99",
"Title": null,
"Modified": "2022-06-02T08:20:16Z",
"Created": "2022-06-02T08:20:16Z",
"AuthorId": 1282,
"EditorId": 1282,
"OData__UIVersionString": "1.0",
"Attachments": false,
"GUID": "c3395b35-a981-4754-abb5-8b4b0fe65a51",
"ComplianceAssetId": null,
"Aadhar_x0020_Nuber": 999955183433,
"NameId": 846,
"NameStringId": "846",
"Age": 37,
"Gender": "M",
"Phone": 2821096353,
"Father_x0020_Name": "Mr. Pandey",
"Email": "rpandey#mailserver.com",
"City": "Mumbai",
"State": "Maharastra"
},
{
"odata.type": "SP.Data.Aadhar_x005f_DataListItem",
"odata.id": "29ba7f05-52e8-4ded-b3e5-22a9b3001d97",
"odata.etag": "\"2\"",
"odata.editLink": "Web/Lists(guid'f57b8a37-9a12-48fa-ae4a-f2c360611fd2')/Items(5)",
"Name#odata.navigationLinkUrl": "Web/Lists(guid'f57b8a37-9a12-48fa-ae4a-f2c360611fd2')/Items(5)/Name",
"Name": {
"odata.type": "SP.Data.UserInfoItem",
"odata.id": "cdce69d7-a601-4c9f-ad03-0a85eccb510b",
"Title": "Namita Rastogi"
},
"FileSystemObjectType": 0,
"Id": 5,
"ServerRedirectedEmbedUri": null,
"ServerRedirectedEmbedUrl": "",
"ID": 5,
"ContentTypeId": "0x0100CAEC71E55732C14BA36095D2FA8E6CA80037B4C7B1E7CFFA4D83E55D30CD77AC99",
"Title": null,
"Modified": "2022-06-09T07:25:17Z",
"Created": "2022-06-02T08:21:46Z",
"AuthorId": 1282,
"EditorId": 1282,
"OData__UIVersionString": "2.0",
"Attachments": false,
"GUID": "7a7d7906-442e-41eb-9f17-16f729fbb310",
"ComplianceAssetId": null,
"Aadhar_x0020_Nuber": 999990501894,
"NameId": 849,
"NameStringId": "849",
"Age": 40,
"Gender": "F",
"Phone": 2821096351,
"Father_x0020_Name": "Mr. Kapoor",
"Email": "anisha#gmail.com",
"City": "Bangalore",
"State": "Karnataka"
}
]
Expected Output:-
[
{
"Title": "Ankit Singh",
"Aadhar_x0020_Nuber": ,
"Age": ,
"Gender": "",
"Phone": ,
"Father_x0020_Name": "",
"Email": "",
"City": "",
"State": ""
},
{
"Title": "",
"Aadhar_x0020_Nuber": ,
"Age": ,
"Gender": "F",
"Phone": ,
"Father_x0020_Name": "",
"Email": "",
"City": "",
"State": ""
},
{
"Title": "",
"Aadhar_x0020_Nuber": ,
"Age": ,
"Gender": "M",
"Phone": ,
"Father_x0020_Name": "",
"Email": "",
"City": "",
"State": ""
},
{
"Title": "Shikhar Saxena",
"Aadhar_x0020_Nuber": ,
"Age": ,
"Gender": "",
"Phone": ,
"Father_x0020_Name": "",
"Email": "",
"City": "",
"State": ""
},
{
"Title": "",
"Aadhar_x0020_Nuber": ,
"Age": ,
"Gender": "",
"Phone": 2821096351,
"Father_x0020_Name": "",
"Email": "",
"City": "",
"State": ""
}
]
You are assigning a new value to the jsonOutput1 and jsonOutput2 everytime. You want to add to the existing object, in that case you need to change the lines:
jsonOutput1 = { [j]: d[0]["Name"].Title };
to
jsonOutput1[j] = d[0]["Name"].Title;
Similarly update the code for your jsonOutput2 line as well.
You can refer to this MDN JavaScript Guide Documentation and refer to the part where there demonstrate how to create additional properties in an existing object.
Hopefully, this will work.

compare objects of same array and group their some properties when specific property matched with other object

I have an array of object as following :
"orders": [
{
"orderID": 1,
"fullName": "xyz",
"email": "xyz#gmail.com",
"phone": "12345",
"flatNo": "A-5",
"complex": "tara tra",
"landmark": null,
"street": null,
"area": "",
"city": "",
"productID": 2,
"name": "curd",
"price": 52,
"image": "curd.png",
"quantity": 1
},
{
"orderID": 1,
"fullName": "xyz",
"email": "xyz#gmail.com",
"phone": "12345",
"flatNo": "A-5",
"complex": "tara tra",
"landmark": null,
"street": null,
"area": "",
"city": "",
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 1
},
{
"orderID": 2,
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 3
}
]
Here if the orderID is same for the object I want to merge those object into a single object and create the product information into an array of an object within the main array
Here is the output which I am looking for
"orders": [
{
"orderID": 1,
"fullName": "xyz",
"email": "xyz#gmail.com",
"phone": "12345",
"flatNo": "A-5",
"complex": "tara tra",
"landmark": null,
"street": null,
"area": "",
"city": "",
"products": [
{
"productID": 2,
"name": "curd",
"price": 52,
"image": "curd.png",
"quantity": 1
},
{
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 1
}
]
},
{
"orderID": 2,
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 3
}
]
basically I want to combine product information if the order ID is the same.
You'll have an easy time if you use my library for this.
const data = { orders: [ { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 2, "name": "curd", "price": 52, "image": "curd.png", "quantity": 1 }, { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 1 }, { "orderID": 2, "fullName": "velocity", "email": "velocity#gmail.com", "phone": "999999", "flatNo": "b-863", "complex": "tara tra", "landmark": "kaskd", "street": "asdasd", "area": "rob city", "city": "asda", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 3 } ] }
const { pipe, assign, reduce, get, pick, omit } = rubico
const productKeys = ['productID', 'name', 'price', 'image', 'quantity']
const addOrderToMap = (m, order) => {
if (m.has(order.orderID)) {
m.get(order.orderID).products.push(pick(productKeys)(order))
} else {
m.set(order.orderID, {
...omit(productKeys)(order),
products: [pick(productKeys)(order)],
})
}
return m
}
const groupedByOrderID = assign({
orders: pipe([ // assign orders key
get('orders'), // data => orders
reduce(addOrderToMap, new Map()), // orders => Map { orderID -> orderWithProducts }
m => m.values(), // Map { orderID -> orderWithProducts } -> iterator { orderWithProducts }
Array.from, // iterator { orderWithProducts } -> [orderWithProducts]
]),
})(data)
console.log(groupedByOrderID)
<script src="https://unpkg.com/rubico/index.js"></script>
I've commented the code for you, here's the tour if you'd like to learn more.
Just in case if you want to do it through plain JavaScript you can make use of reduce:
var data=[ { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 2, "name": "curd", "price": 52, "image": "curd.png", "quantity": 1 }, { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 1 }, { "orderID": 2, "fullName": "velocity", "email": "velocity#gmail.com", "phone": "999999", "flatNo": "b-863", "complex": "tara tra", "landmark": "kaskd", "street": "asdasd", "area": "rob city", "city": "asda", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 3 } ];
var result = Object.values(data.reduce((acc, {productID, name, price,image, quantity, ...rest})=>{
acc[rest.orderID] = acc[rest.orderID] || {...rest, products:[]};
acc[rest.orderID].products.push({productID, name, price,image, quantity});
return acc;
},{}));
console.log(result);

filter array of objects with dates

I am trying to fetch the data and store into 2 separate arrays from given below array of objects which meet following two conditions
From the current Array of objects, I want to only get the objects whose month is the current month.
another array for past 7 days
How can I do soo?
can I get any tip to work with dates as I am not soo good with it?
{
"status": "success",
"results": 10,
"orders": [
{
"orderID": 1,
"orderStatus": 1,
"purAmt": 1000,
"orderDate": "2020-06-14T03:23:20.000Z",
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"products": [
{
"productID": 1,
"name": "lassi",
"price": 62,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 5
},
{
"productID": 2,
"name": "curd",
"price": 55,
"image": "curd.png",
"quantity": 9
}
]
},
{
"orderID": 2,
"orderStatus": 1,
"purAmt": 1000,
"orderDate": "2020-06-14T03:24:32.000Z",
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"products": [
{
"productID": 6,
"name": "chicken chilly",
"price": 65,
"image": "images\\PIwc5RQ7s-conn2.PNG",
"quantity": 1
},
{
"productID": 7,
"name": "buteer flyyy",
"price": 70,
"image": "images\\GvIgYj-lO-conn2.PNG",
"quantity": 2
}
]
},
{
"orderID": 4,
"orderStatus": 1,
"purAmt": 250,
"orderDate": "2020-06-15T09:04:45.000Z",
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"products": [
{
"productID": 1,
"name": "lassi",
"price": 62,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 1
},
{
"productID": 2,
"name": "curd",
"price": 55,
"image": "curd.png",
"quantity": 1
}
]
},
{
"orderID": 5,
"orderStatus": 2,
"purAmt": 250,
"orderDate": "2020-05-15T10:33:59.000Z",
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"products": [
{
"productID": 2,
"name": "curd",
"price": 55,
"image": "curd.png",
"quantity": 1
}
]
},
{
"orderID": 6,
"orderStatus": 2,
"purAmt": 250,
"orderDate": "2020-06-15T10:41:53.000Z",
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"products": [
{
"productID": 2,
"name": "curd",
"price": 55,
"image": "curd.png",
"quantity": 1
}
]
},
{
"orderID": 7,
"orderStatus": 2,
"purAmt": 250,
"orderDate": "2020-06-15T10:44:58.000Z",
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"products": [
{
"productID": 2,
"name": "curd",
"price": 55,
"image": "curd.png",
"quantity": 1
}
]
},
{
"orderID": 8,
"orderStatus": 2,
"purAmt": 250,
"orderDate": "2020-06-15T11:00:57.000Z",
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"products": [
{
"productID": 2,
"name": "curd",
"price": 55,
"image": "curd.png",
"quantity": 1
}
]
},
{
"orderID": 9,
"orderStatus": 1,
"purAmt": 250,
"orderDate": "2020-06-15T11:01:50.000Z",
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"products": [
{
"productID": 2,
"name": "curd",
"price": 55,
"image": "curd.png",
"quantity": 1
}
]
}
]
}
The Date object here will help a lot. To get orders this month you could try something like:
orders.filter(order => {
const orderDate = new Date(order.orderDate);
const today = new Date();
const isThisYear = orderDate.getFullYear() === today.getFullYear()
const isThisMonth = orderDate.getMonth() === today.getMonth();
return isThisYear && isThisMonth;
})
And to get in the last 7 days you could try something like:
orders.filter(order => {
const orderDate = Date.parse(order.orderDate); // in milliseconds
const today = Date.now(); // in milliseconds
const millisecondsInAWeek = 604800000;
return orderDate > today - millisecondsInAWeek;
})

How to add a text input, where a user can filter the list of students by their name (both first and last name)

I'm trying to create a text search where I can filter through the names from an api.
It should look something like this:
https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/part3.mp4
I'm able to fetch everything from the api successfully I'm just having a hard time creating a filter to search through the first names and last names.
My API looks like this:
https://www.hatchways.io/api/assessment/students
fetch(url).then((resp) => resp.json()).then(function(data) {
let students = data.students;
return students.map(function(student) {
let values = student.grades;
let firstNames = student.firstName;
var sum = 0;
for (var i = 0; i < values.length; i++) {
sum += parseInt(values[i], 10); //don't forget to add the base
}
var avg = sum / values.length;
let li = createNode('li'),
img = createNode('img'),
span = createNode('span');
img.src = student.pic;
span.innerHTML = `<b><li>${firstNames} ${student.lastName}</li></b>
<li>${student.company} </li>
<li>${student.email} </li>
<li>Average: ${avg}</li>`;
})
})
.catch(function(error) {
console.log(JSON.stringify(error));
})
First we fix your code so it runs and produces valid HTML (spans do not have LIs)
Use the first LI content to filter using a dynamic regular expression.
const data = JSON.parse(`{ "students": [ { "city": "Fushë-Muhurr", "company": "Yadel", "email": "iorton0#imdb.com", "firstName": "Ingaberg", "grades": [ "78", "100", "92", "86", "89", "88", "91", "87" ], "id": "1", "lastName": "Orton", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/voluptasdictablanditiis.jpg", "skill": "Oracle" }, { "city": "Sanghan", "company": "Avamm", "email": "cboards1#weibo.com", "firstName": "Clarke", "grades": [ "75", "89", "95", "93", "99", "82", "89", "76" ], "id": "2", "lastName": "Boards", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/voluptasautreprehenderit.jpg", "skill": "Sports" }, { "city": "Kugesi", "company": "Skalith", "email": "lromanet2#wired.com", "firstName": "Laurens", "grades": [ "88", "90", "79", "82", "81", "99", "94", "73" ], "id": "3", "lastName": "Romanet", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/aspernaturnonsapiente.jpg", "skill": "Employee Handbooks" }, { "city": "Krajan", "company": "Mybuzz", "email": "bskitt3#aboutads.info", "firstName": "Berti", "grades": [ "88", "93", "92", "81", "95", "98", "77", "94" ], "id": "4", "lastName": "Skitt", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/autautdeserunt.jpg", "skill": "Nutrition Education" }, { "city": "Huiqi", "company": "Avavee", "email": "msummerley4#craigslist.org", "firstName": "Mureil", "grades": [ "71", "81", "72", "92", "79", "82", "91", "90" ], "id": "5", "lastName": "Summerley", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/consequaturdelectusquis.jpg", "skill": "ISO 14971" }, { "city": "Jianghong", "company": "Twinte", "email": "rcoryndon5#cargocollective.com", "firstName": "Robbyn", "grades": [ "97", "92", "72", "99", "92", "92", "79", "96" ], "id": "6", "lastName": "Coryndon", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/autautdeserunt.jpg", "skill": "Cinema 4D" }, { "city": "Sanxi", "company": "Buzzster", "email": "seykel6#examiner.com", "firstName": "Sheena", "grades": [ "74", "95", "75", "95", "85", "97", "88", "85" ], "id": "7", "lastName": "Eykel", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/utquamut.jpg", "skill": "Ulead VideoStudio" }, { "city": "Huancheng", "company": "Edgeblab", "email": "mewen7#ycombinator.com", "firstName": "Minnnie", "grades": [ "80", "100", "97", "78", "99", "99", "76", "85" ], "id": "8", "lastName": "Ewen", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/nesciuntrerumlibero.jpg", "skill": "Vulcan" }, { "city": "Luoxiong", "company": "Fadeo", "email": "riban8#hubpages.com", "firstName": "Rory", "grades": [ "70", "100", "75", "96", "83", "90", "94", "92" ], "id": "9", "lastName": "Iban", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/autemporroplaceat.jpg", "skill": "EE4" }, { "city": "Toulon", "company": "Yakidoo", "email": "lroxby9#cam.ac.uk", "firstName": "Lenna", "grades": [ "70", "99", "81", "83", "78", "95", "81", "76" ], "id": "10", "lastName": "Roxby", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/doloribusquitempora.jpg", "skill": "LPS" }, { "city": "Lazo", "company": "Photolist", "email": "rfitzalana#parallels.com", "firstName": "Rosalynd", "grades": [ "98", "93", "78", "87", "99", "89", "97", "81" ], "id": "11", "lastName": "FitzAlan", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/utquamut.jpg", "skill": "Geography" }, { "city": "Bichura", "company": "Babblestorm", "email": "srapellib#adobe.com", "firstName": "Stephanie", "grades": [ "83", "97", "70", "96", "75", "98", "90", "71" ], "id": "12", "lastName": "Rapelli", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/enimpariaturoptio.jpg", "skill": "Identity Management" }, { "city": "Chvalšiny", "company": "Mynte", "email": "mmacdirmidc#plala.or.jp", "firstName": "Maire", "grades": [ "87", "73", "85", "98", "73", "95", "75", "97" ], "id": "13", "lastName": "MacDirmid", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/aspernaturnonsapiente.jpg", "skill": "Outdoor Advertising" }, { "city": "Itaparica", "company": "Photospace", "email": "nshepherdd#desdev.cn", "firstName": "Nicoline", "grades": [ "90", "73", "88", "95", "71", "100", "80", "86" ], "id": "14", "lastName": "Shepherd", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/nonipsaet.jpg", "skill": "Amazon VPC" }, { "city": "Praia da Vitória", "company": "Vitz", "email": "ythornse#github.com", "firstName": "Yoshi", "grades": [ "78", "78", "96", "92", "80", "82", "91", "99" ], "id": "15", "lastName": "Thorns", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/voluptasdictablanditiis.jpg", "skill": "DMR" }, { "city": "Sambir", "company": "Twitterwire", "email": "mtothef#shutterfly.com", "firstName": "Marna", "grades": [ "88", "74", "76", "89", "75", "97", "75", "86" ], "id": "16", "lastName": "Tothe", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/utquamut.jpg", "skill": "PFI" }, { "city": "Sarulla", "company": "Blogpad", "email": "okearyg#g.co", "firstName": "Orelia", "grades": [ "78", "92", "86", "80", "82", "95", "76", "84" ], "id": "17", "lastName": "Keary", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/enimpariaturoptio.jpg", "skill": "General Surgery" }, { "city": "Ochakovo-Matveyevskoye", "company": "Mydeo", "email": "mswaith#cafepress.com", "firstName": "Moses", "grades": [ "84", "82", "92", "74", "87", "98", "86", "73" ], "id": "18", "lastName": "Swait", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/velitnonquibusdam.jpg", "skill": "Sales Tax" }, { "city": "Youxi Chengguanzhen", "company": "Avaveo", "email": "fnusseyi#skyrock.com", "firstName": "Fonsie", "grades": [ "100", "75", "84", "91", "100", "97", "98", "87" ], "id": "19", "lastName": "Nussey", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/remtemporavelit.jpg", "skill": "Urbanism" }, { "city": "Limoges", "company": "Tazzy", "email": "srydingsj#phoca.cz", "firstName": "Skelly", "grades": [ "89", "81", "77", "93", "96", "96", "70", "79" ], "id": "20", "lastName": "Rydings", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/etporroalias.jpg", "skill": "IFTA" }, { "city": "Łobżenica", "company": "Quatz", "email": "obrennekek#yellowbook.com", "firstName": "Olly", "grades": [ "81", "74", "77", "82", "74", "88", "86", "87" ], "id": "21", "lastName": "Brenneke", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/velitnonquibusdam.jpg", "skill": "ATM Networks" }, { "city": "Divo", "company": "Gigazoom", "email": "nbadwickl#nifty.com", "firstName": "Norby", "grades": [ "73", "99", "91", "92", "85", "96", "95", "73" ], "id": "22", "lastName": "Badwick", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/delenitiestdolorum.jpg", "skill": "Media Relations" }, { "city": "Sortavala", "company": "Eamia", "email": "mmichiem#nifty.com", "firstName": "Melody", "grades": [ "100", "83", "76", "71", "93", "95", "73", "88" ], "id": "23", "lastName": "Michie", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/sitlaborecorrupti.jpg", "skill": "PC Games" }, { "city": "Taupo", "company": "Midel", "email": "jwillougheyn#psu.edu", "firstName": "Janice", "grades": [ "71", "80", "83", "99", "91", "95", "81", "75" ], "id": "24", "lastName": "Willoughey", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/dolordoloremassumenda.jpg", "skill": "Kondor+" }, { "city": "Krajandadapmulyo", "company": "Wikibox", "email": "ggallymoreo#mashable.com", "firstName": "Geraldine", "grades": [ "97", "71", "89", "85", "85", "87", "92", "75" ], "id": "25", "lastName": "Gallymore", "pic": "https://storage.googleapis.com/hatchways-app.appspot.com/assessments/data/frontend/images/sitlaborecorrupti.jpg", "skill": "WTL" } ] }`);
let students = data.students;
students.forEach(function(student) {
let values = student.grades;
let firstNames = student.firstName;
let sum = values.reduce((a,b) => +a + +b, 0); //convert to ints before summing
let avg = (sum / values.length).toFixed(2);
let card = document.createElement("div"), // wrapper
li = document.createElement('li'),
img = document.createElement('img'),
ul = document.createElement('ul');
ul.classList.add("filter");
img.src = student.pic;
ul.innerHTML = `<li><b>${firstNames} ${student.lastName}</b></li>
<li>${student.company} </li>
<li>${student.email} </li>
<li>Average: ${avg}</li>`;
card.appendChild(img);
card.appendChild(ul);
document.getElementById("container").appendChild(card)
})
document.getElementById("filter").addEventListener("input", (e) => {
let val = e.target.value;
re = new RegExp(val.split(" ").join("|"), "gi"); // creates /joe|blow/gi
document.querySelectorAll("ul.filter").forEach(ele => {
const words = ele.firstChild.textContent.split(' ');
let found = words.some(c => re.test(c));
ele.closest("div").style.display = found ? "" : "none"; // toggle the card
});
})
//Alternatives for the textContent:
// ul.setAttribute("data-filter", `${firstNames} ${student.lastName}`);
// `${firstNames} ${student.lastName}`.split(" ").forEach(name => ul.classList.add(name) )
ul {list-style: none}
#container img { float:left; padding:5px }
#filter { position:fixed; margin-left:300px }
<input id="filter" />
<div id="container"></div>

How to avoid JSON pointer in JavaScript with do not use json.stringify?

I want to copy employee to a new employee and not point to an old employee.
I try to use:
newEmployees.assign([{}].employees); <br>
newEmployees = [{...employees}]; <br>
They are pointing to an old employee.
const employees = [
{
"id": "1001",
"firstname": "Luke",
"lastname": "Skywalker",
"company": "Walt Disney",
"salary": "40000"
},
{
"id": "1002",
"firstname": "Tony",
"lastname": "Stark",
"company": "Marvel",
"salary": "1000000"
},
{
"id": "1003",
"firstname": "Somchai",
"lastname": "Jaidee",
"company": "Love2work",
"salary": "20000"
},
{
"id": "1004",
"firstname": "Monkey D",
"lastname": "Luffee",
"company": "One Piece",
"salary": "9000000"
}
];
let newEmployees = [{}];
newEmployees[0] = employees[3]; // assign
employees[3]['firstname'] = 'Arhus'; // change old employees
console.log(newEmployees); //firstname: 'Arhus' - shows employees content
Thank you so much.
Just use spread while assigning the value like this
const employees = [
{
"id": "1001",
"firstname": "Luke",
"lastname": "Skywalker",
"company": "Walt Disney",
"salary": "40000"
},
{
"id": "1002",
"firstname": "Tony",
"lastname": "Stark",
"company": "Marvel",
"salary": "1000000"
},
{
"id": "1003",
"firstname": "Somchai",
"lastname": "Jaidee",
"company": "Love2work",
"salary": "20000"
},
{
"id": "1004",
"firstname": "Monkey D",
"lastname": "Luffee",
"company": "One Piece",
"salary": "9000000"
}
];
let newEmployees = [{}];
newEmployees[0] = { ...employees[3] };
employees[3]['firstname'] = 'Arhus'; // change employee
console.log(newEmployees); //firstname is still Monkey D
Just use .map and object spread:
const employees = [
{
"id": "1001",
"firstname": "Luke",
"lastname": "Skywalker",
"company": "Walt Disney",
"salary": "40000"
},
{
"id": "1002",
"firstname": "Tony",
"lastname": "Stark",
"company": "Marvel",
"salary": "1000000"
},
{
"id": "1003",
"firstname": "Somchai",
"lastname": "Jaidee",
"company": "Love2work",
"salary": "20000"
},
{
"id": "1004",
"firstname": "Monkey D",
"lastname": "Luffee",
"company": "One Piece",
"salary": "9000000"
}
];
const newEmployees = employees.map(employee => ({...employee}));
employees[3].firstname = 'Arhus';
console.log(newEmployees[3]);
console.log(employees[3]);
While assigning value you can use Object.assign or Object.clone
Consider the following snippet:
const employees = [
{
"id": "1001",
"firstname": "Luke",
"lastname": "Skywalker",
"company": "Walt Disney",
"salary": "40000"
},
{
"id": "1002",
"firstname": "Tony",
"lastname": "Stark",
"company": "Marvel",
"salary": "1000000"
},
{
"id": "1003",
"firstname": "Somchai",
"lastname": "Jaidee",
"company": "Love2work",
"salary": "20000"
},
{
"id": "1004",
"firstname": "Monkey D",
"lastname": "Luffee",
"company": "One Piece",
"salary": "9000000"
}
];
let newEmployees = [{}];
newEmployees[0] = Object.assign({}, employees[3]);
employees[3]['firstname'] = 'Arhus';
console.log(newEmployees);
I understand you want to copy the object value and don't want to use stringify. Stringifying the object and parsing it back to JSON is one way,
cloning the object is another method and I believe spreading also works.
But if you prefer convenience you may want to take a look at "lodash" library's _.clone and _.clonedeep methods.
Also if you'd like to read more refer :
Lodash .clone and .cloneDeep behaviors
How to copy an object by value, not by reference

Categories

Resources