accessing Javascript object - javascript

may be a simple issue but cannot seem to solve it after some searching as well :) .. The scenario is as follows:
Using PhoneGap, am receiving a json object via Ajax using jquery. the object needs to be displayed on a next screen (first is the Search page and the next is the Search result page).
when the object is received, it is being saved in the sessionStorage variable (e.g. sessionStorage.result = data).
but when it is tried to be accessed on the next page, it gives an error saying that the property is unknown. e.g.
var result = sessionStorage.result;
alert(result.response.businesses[0].name);
have also tried:
alert($(result.response.businesses[0].name));
it says that the property is unknow. the basic structure of the json is as follows:
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [
{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}
]
Any help appreciated.

You are wrongly accessing that value,
Try,
var result = JSON.parse(sessionStorage.result);
alert($(result.businesses[0].name));

in your json codes missing } your codes must be like that
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}]
}
}
alert(result.response.businesses[0].name); // it will work i think. no error
also look sessionstroge is there any data

Your Json string is not a valid JSON format plz check the format
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}]
}
}

Related

Fetch JSON data that has multiple pages?

I'm making a fetch to the API to grab the total number of players, the returned data is below:
"data": [
{
"id": 558,
"first_name": "Dave",
"height_feet": null,
"height_inches": null,
"last_name": "Jamerson",
"position": "",
"team": {
"id": 11,
"abbreviation": "HOU",
"city": "Houston",
"conference": "West",
"division": "Southwest",
"full_name": "Houston Rockets",
"name": "Rockets"
},
"weight_pounds": null
},
{
"id": 559,
"first_name": "Scott",
"height_feet": null,
"height_inches": null,
"last_name": "Brooks",
"position": "",
"team": {
"id": 18,
"abbreviation": "MIN",
"city": "Minnesota",
"conference": "West",
"division": "Northwest",
"full_name": "Minnesota Timberwolves",
"name": "Timberwolves"
},
"weight_pounds": null
},
{
"id": 560,
"first_name": "Rolando",
"height_feet": null,
"height_inches": null,
"last_name": "Blackman",
"position": "",
"team": {
"id": 7,
"abbreviation": "DAL",
"city": "Dallas",
"conference": "West",
"division": "Southwest",
"full_name": "Dallas Mavericks",
"name": "Mavericks"
},
"weight_pounds": null
},
{
"id": 561,
"first_name": "Avery",
"height_feet": null,
"height_inches": null,
"last_name": "Johnson",
"position": "",
"team": {
"id": 8,
"abbreviation": "DEN",
"city": "Denver",
"conference": "West",
"division": "Northwest",
"full_name": "Denver Nuggets",
"name": "Nuggets"
},
"weight_pounds": null
},
{
"id": 562,
"first_name": "Rod",
"height_feet": null,
"height_inches": null,
"last_name": "Higgins",
"position": "",
"team": {
"id": 10,
"abbreviation": "GSW",
"city": "Golden State",
"conference": "West",
"division": "Pacific",
"full_name": "Golden State Warriors",
"name": "Warriors"
},
"weight_pounds": null
},
{
"id": 566,
"first_name": "Sam",
"height_feet": null,
"height_inches": null,
"last_name": "Vincent",
"position": "",
"team": {
"id": 22,
"abbreviation": "ORL",
"city": "Orlando",
"conference": "East",
"division": "Southeast",
"full_name": "Orlando Magic",
"name": "Magic"
},
"weight_pounds": null
},
{
"id": 567,
"first_name": "Isiah",
"height_feet": null,
"height_inches": null,
"last_name": "Thomas",
"position": "",
"team": {
"id": 9,
"abbreviation": "DET",
"city": "Detroit",
"conference": "East",
"division": "Central",
"full_name": "Detroit Pistons",
"name": "Pistons"
},
"weight_pounds": null
}
],
"meta": {
"total_pages": 39,
"current_page": 1,
"next_page": 2,
"per_page": 100,
"total_count": 3828
}
Problem is, the API only allows for a max of 100 results. As you can see in the "meta" object at the bottom, there is a total_count of 3828 and 39 pages, how would I access the other pages and get all 3828 results? currently I only get the first page with 100 results when I fetch.
const getPlayers = () => {
fetch(`https://www.balldontlie.io/api/v1/players?per_page=100`)
.then(res => res.json())
.then(data => dispatch(playerActions.getPlayers(data)));
}

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);

How Can I able to display following data is vue js?

My json response is
{"status": true, "data": {"basic": {"name": "haji", "dob": "2018-01-01", "gender": "male", "created_at": "2018-01-08T13:38:49.767Z", "firstname": "Ah", "lastname": "Sh", "userType": "Agent", "actor": 1, "username": "ashu", "contact": {"email": "ah#gmail.com", "phone": 863249517, "address": null}, "is_new": false, "is_email_verified": true, "is_phone_verified": true}, "wallet": {"amount": 144.0, "tds": 6.0}, "clan": null, "balance_lisitings": 48, "clan_status": false, "listings": [{"pid": 36, "name": "Labs", "website": "Labs", "category": {"name": "Education"}, "location": {"lat": 9.52766533190131, "lon":
76.8221354484558, "state": "Kerala", "country": "India", "district": {"id": 1, "name": "Kottayam"}, "city": {"id": 1, "name": "Kanjirappally"}, "place": {"id": 1, "name": "Koovappally"}}, "package": 0, "contact": {"email": "ah#gmail.com", "phone": 8986234851, "address": {"country": "India", "state": "Kerala", "name": "aloh", "pincode": 686895, "streetAddress": "Kottayam\nKanjirappally", "locality": "Koovappally", "city": "Koovappally"}}, "about": " IT company."}, {"pid": 37, "name": " Louis", "website": "ouis", "category": {"name": "Education"}, "location": {"lat": 10.0273434437709, "lon": 76.5288734436035, "state": "Kerala", "country": "India", "district": {"id": 1, "name": "Kottayam"}, "city": {"id": 1, "name": "Kanjirappally"}, "place": {"id": 1, "name": "Koovappally"}}, "package": 0, "contact": {"email": "soew988#gmail.com", "phone": 989756240, "address": {"country": "India", "state": "Kerala", "name": "allen45", "pincode": 686518, "streetAddress": "Sppally", "locality": "Koovappally", "city": "Koovappally"}}, "about": "fsdbgfnvb cvc"}], "total_listings": 2}}
========================================================================
My vue js script is
<script>
new Vue({
el: '#listings' ,
data: {
data: [],
},
mounted() {
this.$nextTick(function() {
var self = this;
$.ajax({
url: "https://",
method: "GET",
dataType: "JSON",
success: function (e) {
self.data = e.data;
},
});
})
},
})
</script>
My html code is
<div id="listings">
<h1>{{basic.name}}</h1>
<h2>{{basic.dob}}</h2>
like wise all data
</div>
Can anybody please help me to display the same. I am weak in js. This is the data I am getting I need to display the above data in vue js. I store all the data to a variable data[]. From it, how can I able to display the same?
One thing you'll need is a v-if to keep things from rendering when there's no data.
You have a data variable and basic is inside it. As you have it, all the things you want to include are inside it, so you will have a lot of things like data.basic.name.
const e = {
"status": true,
"data": {
"basic": {
"name": "haji",
"dob": "2018-01-01",
"gender": "male",
"created_at": "2018-01-08T13:38:49.767Z",
"firstname": "Ah",
"lastname": "Sh",
"userType": "Agent",
"actor": 1,
"username": "ashu",
"contact": {
"email": "ah#gmail.com",
"phone": 863249517,
"address": null
},
"is_new": false,
"is_email_verified": true,
"is_phone_verified": true
},
"wallet": {
"amount": 144.0,
"tds": 6.0
},
"clan": null,
"balance_lisitings": 48,
"clan_status": false,
"listings": [{
"pid": 36,
"name": "Labs",
"website": "Labs",
"category": {
"name": "Education"
},
"location": {
"lat": 9.52766533190131,
"lon": 76.8221354484558,
"state": "Kerala",
"country": "India",
"district": {
"id": 1,
"name": "Kottayam"
},
"city": {
"id": 1,
"name": "Kanjirappally"
},
"place": {
"id": 1,
"name": "Koovappally"
}
},
"package": 0,
"contact": {
"email": "ah#gmail.com",
"phone": 8986234851,
"address": {
"country": "India",
"state": "Kerala",
"name": "aloh",
"pincode": 686895,
"streetAddress": "Kottayam\nKanjirappally",
"locality": "Koovappally",
"city": "Koovappally"
}
},
"about": " IT company."
}, {
"pid": 37,
"name": " Louis",
"website": "ouis",
"category": {
"name": "Education"
},
"location": {
"lat": 10.0273434437709,
"lon": 76.5288734436035,
"state": "Kerala",
"country": "India",
"district": {
"id": 1,
"name": "Kottayam"
},
"city": {
"id": 1,
"name": "Kanjirappally"
},
"place": {
"id": 1,
"name": "Koovappally"
}
},
"package": 0,
"contact": {
"email": "soew988#gmail.com",
"phone": 989756240,
"address": {
"country": "India",
"state": "Kerala",
"name": "allen45",
"pincode": 686518,
"streetAddress": "Sppally",
"locality": "Koovappally",
"city": "Koovappally"
}
},
"about": "fsdbgfnvb cvc"
}],
"total_listings": 2
}
};
new Vue({
el: '#listings',
data: {
data: [],
},
mounted() {
const self = this;
self.data = e.data;
},
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="listings" v-if="data.basic">
<h1>{{data.basic.name}}</h1>
<h2>{{data.basic.dob}}</h2>
like wise all data
</div>
Any data nested inside the data (and computed) property is available in the template between the {{ and }} tags.
For example:
Vue.element('my-element', {
template:
'<h1>This is an example!</h1>' +
'<h2>{{ msg }}</h2>'
data: function () {
return {
msg: 'default message'
}
},
So in your case, with nested properties it is exactly the same as you would access them in javascript:
Vue.element('my-element', {
template:
'<h1>This is an example!</h1>' +
'<h2>{{ data.wallet.amount }}</h2>'
'<h2 v-for="listing in listings" :key="listing.pid">{{ listing.name }}</h2>'
}
data: function () {
return {
data: []
}
},
Note
The data object should be returned from a function, from the original docs:
When defining a component, data must be declared as a function that returns the initial data object, because there will be many instances created using the same definition. If we use a plain object for data, that same object will be shared by reference across all instances created! By providing a data function, every time a new instance is created we can call it to return a fresh copy of the initial data. (https://v2.vuejs.org/v2/api/#data)
Further reading
I would advise you to read the Vue guide, especially the sections about
Declarative Rendering, Conditionals and Loops and Template Syntax
EDIT
While I was writing my answer, I see you edited your question.
Change your html to this:
<div id="listings">
<h1>{{data.basic.name}}</h1>
<h2>{{data.basic.dob}}</h2>
like wise all data
</div>

Loop through json data in Handlebars

On the handlebars website I can see how to loop through an array but I'm trying to look through an array object and having no luck.
Here's my data, which I am getting back using jquery and a jsonp command.
[
{
"id": 95,
"user_id": 6,
"status": 1,
"name": "Lost & Co",
"country": {
"code": "GB",
"name": "United Kingdom"
},
"city": "London",
"venue": "Lost & Co",
"fsqid": "512fb191e4b0f660fda426eb",
"address": "160 Putney High Street",
"postcode": null,
"lat": "51.461322924772",
"lng": "-0.21689196269354",
"phone": "+442087802235",
"description": null,
"date": "2014-05-10",
"time": "",
"image": null,
"image_thumb": null,
"website": "",
"twitter": null,
"tickets": "",
"fb_event": null,
"created_at": "2014-04-24 12:20:09",
"updated_at": "2014-04-24 12:20:09"
},
{
"id": 96,
"user_id": 6,
"status": 1,
"name": "Lost & Co",
"country": {
"code": "GB",
"name": "United Kingdom"
},
"city": "London",
"venue": "Lost & Co",
"fsqid": "512fb191e4b0f660fda426eb",
"address": "160 Putney High Street",
"postcode": null,
"lat": "51.461322924772",
"lng": "-0.21689196269354",
"phone": "+442087802235",
"description": null,
"date": "2014-05-24",
"time": "",
"image": null,
"image_thumb": null,
"website": "",
"twitter": null,
"tickets": "",
"fb_event": null,
"created_at": "2014-04-24 12:20:57",
"updated_at": "2014-04-24 12:20:57"
},
{
"id": 94,
"user_id": 6,
"status": 1,
"name": "Lost Society",
"country": {
"code": "GB",
"name": "United Kingdom"
},
"city": "London",
"venue": "Lost Society",
"fsqid": "4bbcf543593fef3b35de0256",
"address": "697 Wandsworth Rd",
"postcode": "SW8 3JF",
"lat": "51.467991033249",
"lng": "-0.14425992965698",
"phone": "+442076526526",
"description": null,
"date": "2014-05-31",
"time": "",
"image": null,
"image_thumb": null,
"website": "http://www.lostsociety.co.uk/index2.html",
"twitter": "lostsocietybar",
"tickets": "",
"fb_event": null,
"created_at": "2014-04-24 12:18:53",
"updated_at": "2014-04-24 12:18:53"
},
{
"id": 97,
"user_id": 6,
"status": 1,
"name": "Campus North",
"country": {
"code": "GB",
"name": "United Kingdom"
},
"city": "Newcastle",
"venue": "Campus North",
"fsqid": "533b05b0498ea89103652747",
"address": "5 Carliol Square",
"postcode": null,
"lat": "54.973037719727",
"lng": "-1.6087431907654",
"phone": null,
"description": null,
"date": "2014-06-12",
"time": "",
"image": null,
"image_thumb": null,
"website": "",
"twitter": null,
"tickets": "",
"fb_event": null,
"created_at": "2014-04-24 17:56:26",
"updated_at": "2014-04-24 17:55:55"
},
{
"id": 91,
"user_id": 6,
"status": 1,
"name": "Glastonbury",
"country": {
"code": "GB",
"name": "United Kingdom"
},
"city": "Pilton",
"venue": "Glastonbury",
"fsqid": null,
"address": null,
"postcode": null,
"lat": null,
"lng": null,
"phone": null,
"description": null,
"date": "2014-06-28",
"time": "",
"image": null,
"image_thumb": null,
"website": "http://www.glastonburyfestivals.co.uk/",
"twitter": null,
"tickets": "",
"fb_event": null,
"created_at": "2014-04-22 12:08:32",
"updated_at": "2014-04-22 13:06:51"
},
{
"id": 92,
"user_id": 6,
"status": 1,
"name": "Glastonbury",
"country": {
"code": "GB",
"name": "United Kingdom"
},
"city": "Pilton",
"venue": "Glastonbury",
"fsqid": null,
"address": null,
"postcode": null,
"lat": null,
"lng": null,
"phone": null,
"description": null,
"date": "2014-06-29",
"time": "",
"image": null,
"image_thumb": null,
"website": "http://www.glastonburyfestivals.co.uk/",
"twitter": null,
"tickets": "",
"fb_event": null,
"created_at": "2014-04-22 12:08:46",
"updated_at": "2014-04-22 13:07:27"
},
{
"id": 80,
"user_id": 6,
"status": 1,
"name": "TBA",
"country": {
"code": "ES",
"name": "Spain"
},
"city": "Ibiza",
"venue": "TBA",
"fsqid": "51fab9b1498e0ced82ae61d0",
"address": "Mediterranean Sea",
"postcode": null,
"lat": "38.970107",
"lng": "1.305714",
"phone": null,
"description": null,
"date": "2014-09-12",
"time": "",
"image": null,
"image_thumb": null,
"website": "",
"twitter": null,
"tickets": "",
"fb_event": null,
"created_at": "2014-02-27 00:41:49",
"updated_at": "2014-02-27 00:41:49"
}
]
I was trying this but it's not working. Have I missed something obvious?
<ul>
{{#each}}
<li>
<h3>{{ venue }}</h3>
</li>
{{/each}}
</ul>
You need to provide a context to that #each:
{{#each .}}
<li>
<h3>{{ venue }}</h3>
</li>
{{/each}}
All you're missing is that you need to let handlebars know that it's the root object as such that you want to iterate over.

Categories

Resources