How to get this jSON data from API with Javascript / AngularJS - javascript

I am working with jSON, an API and AngularJS. I want to get the following data, but I will not know in advanced what the keywords or the dates will be
{
"landscape gardening middlesex": {
"2015-02-12": {
"position": null,
"change": "n/a",
"class": "gray"
},
"2015-03-17": {
"position": "0",
"change": "n/a",
"class": "gray"
}
},
"landscape gardening staines": {
"2015-02-12": {
"position": null,
"change": "n/a",
"class": "gray"
},
"2015-03-17": {
"position": "94",
"change": "n/a",
"class": "green"
}
},
"landscape gardening surrey": {
"2015-02-12": {
"position": null,
"change": "n/a",
"class": "green"
},
"2015-03-17": {
"position": "0",
"change": "n/a",
"class": "gray"
}
}
}
How can i retrieve this using AngularJS ng-repeat Thanks.

create a javascript object and store it somewhere...
you can always stringify it then re-parse it
var myJSON = {
name: "bill",
skills : ["coding", "sleeping", "eating"],
age : 25
};
// this string can be stored anywhere, like even as a string in mySQL.
var string = JSON.stringify( myJSON );
/// Turn Back into JSON obj
var newJSON = JSON.parse(string);
console.log( newJSON.name ); // >> "bill"
/// Hope this helps

Related

how can i fetch data stats value

i have json file in an api source, The json output is as below.
{
"data": {
"metadata": { },
"segments": [
{
"type": "overview",
"attributes": {},
"expiryDate": "2021-07-03T00:25:07.8647619+00:00",
"stats": {
"timePlayed": {
"rank": null,
"percentile": 93,
"displayName": "Time Played",
"displayCategory": "General",
"category": "general",
"metadata": {},
"value": 6635877,
"displayValue": "1,843h 17m",
"displayType": "TimeSeconds"
},
"score": {
"rank": null,
"percentile": 85,
"displayName": "Score",
"displayCategory": "General",
"category": "general",
"metadata": {},
"value": 210790,
"displayValue": "210,790",
"displayType": "Number"
}
}
}
],
"availableSegments": [],
"expiryDate": "2021-07-03T00:25:07.8647619+00:00"
}
}
I want to get the data > segments > stats values ​​in this json output using fetch method. My Codes;
fetch(csgo2, {"headers": {"TRN-Api-Key": "xxxxxxxxxxxxxxxxxxxxxxxxx"}}).then(res => res.json()).then(body => {
const { timePlayed, score} = body.data.segments[0];
console.log(timePlayed.value)//undefined always output console.
})
I'm trying to get the data > segments > score or timesplayed value as in the code block, but I keep getting the undefined error from the console.
what i want to do is get the score or timesplayed value
The issue is you should use body.data.segments[0].stats. The body is an object with a data property, not the data property itself.

How do you delete an empty array from javascript?

For reference I have zero javascript knowledge or any coding knowledge. I typically just hook up applications via IPASS applications that don't require any coding knowledge. However, I found out I need to inject some javascript into the application in order to avoid an error message.
I have the below JSON record.
I need to get rid of the empty array (sorry... if it is not an array but an object? Like I said, no javascript knowledge).
In the below code essentially what I want is to completely delete this line, because there is nothing inside the brackets and it is causing errors:
"lineitemsdata": []
Full JSON record below for reference
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [
{
"id": "5230410841",
"type": "company_to_deal"
}
]
}
},
"dealdata": [
{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [
{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}
],
"DealOwner": [
{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}
],
"NetSuiteCustomerID": 1745
}
Item inside object is called a property. If you (for some reason) have to include the property, but don't want it to have any value you can either set it's value to null or undefined.
I suspect I'm going to get criticized for this, but here is a quick and dirty way of removing this specific problem through string replacement. The 'right' way would be to break down your json into separte objects until you get to the level where the offending object lives, remove it, then rebuild it all back. For what it's worth, here's an alternative to that
let json = {
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [{
"id": "5230410841",
"type": "company_to_deal"
}]
}
},
"dealdata": [{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}],
"DealOwner": [{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}],
"NetSuiteCustomerID": 1745
}
json = JSON.stringify(json)
let strstart = json.indexOf('"lineitemsdata":[]');
let commapos = json.lastIndexOf(',', strstart);
json = json.substr(0, commapos) + " " + json.substr(commapos + 1);
json = json.replace('"lineitemsdata":[]', '');
json = JSON.parse(json)
console.log(json)
You can use this to strip any empty lineitems arrays from your json.
Assuming the reference to your record is json
for(dealIdx in json.dealdata) {
for (resultIdx in json.dealdata[dealIdx].associations["line items"].results) {
let lineItemsData = json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
if (lineItemsData != undefined && lineItemsData.length === 0 ) {
delete json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
}
}
}

Replacing two objects in an array

I am trying to develop a dynamic DraggableFlatList with react native redux, where the updated array from onDragEnd is dispatched to the store. Hence I am trying to create a function where I use the "from" and "to" parameters from the return object from onDragEnd to alter a new array before dispatch. As an example, in the object below, I work with three items, that are objects from the array:
Object {
"data": Array [
Object {
"backgroundColor": "rgb(154, 0, 132)",
"category": "Practical",
"description": "Zero",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.7945943069813785,
"iterations": "",
"key": "0",
},
Object {
"backgroundColor": "rgb(120, 5, 132)",
"category": "Practical",
"description": "One",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.8857539547977513,
"iterations": "",
"key": "1",
},
Object {
"backgroundColor": "rgb(184, 10, 132)",
"category": "Practical",
"description": "Two ",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.11232602853449736,
"iterations": "",
"key": "2",
},
],
"from": 2,
"to": 1,
}
Here I would like the object with the description "two" to change place with the object with the description "one." The keys don't matter because I give them new keys when I render during render.
The function that is doing the replacement looks like this so far:
const dragComplete = (item) => {
let itemArray = item.data;
// from object is going to be replaced with to object and visa vreca
let indexFrom = item.from;
let indexTo = item.to;
let objMovesFrom = itemArray[indexFrom];
let objMovesTo = itemArray[indexTo];
let sortedArray = itemArray;
console.log('Object moves from : ' + objMovesFrom.description);
console.log('Obejct moves to : ' + objMovesTo.description);
sortedArray.map((task, i) => {
if ((i = indexFrom)) {
sortedArray.splice(indexFrom, 1, objMovesTo);
}
if ((i = indexTo)) {
sortedArray.splice(indexTo, 1, objMovesFrom);
}
});
console.log(item);
//dispatch(setTaskList(item.data));
};
I haven't figured to make any sense of it yet...
Thx for the helpful answers!
How about just simply swapping items?..
const dragComplete = item => {
const {
from: sourceIndex,
to: targetIndex,
data: dragList,
} = item;
// // shallow `item.data` copy for a non mutating approach.
// const swapList = Array.from(dragList);
const dragItem = dragList[sourceIndex]; // swapList[sourceIndex];
const swapItem = dragList[targetIndex]; // swapList[targetIndex];
// simply swap items.
// actively mutate `item.data`. // // `item.data` remains unmutated.
dragList[targetIndex] = dragItem; // swapList[targetIndex] = dragItem;
dragList[sourceIndex] = swapItem; // swapList[sourceIndex] = swapItem;
console.log('Object moves from : ' + dragItem.description);
console.log('Object moves to : ' + swapItem.description);
// return swapList;
};
const sample = {
"data": [{
"backgroundColor": "rgb(154, 0, 132)",
"category": "Practical",
"description": "Zero",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.7945943069813785,
"iterations": "",
"key": "0",
}, {
"backgroundColor": "rgb(120, 5, 132)",
"category": "Practical",
"description": "One",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.8857539547977513,
"iterations": "",
"key": "1",
}, {
"backgroundColor": "rgb(184, 10, 132)",
"category": "Practical",
"description": "Two ",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.11232602853449736,
"iterations": "",
"key": "2",
}],
"from": 2,
"to": 1,
};
console.log({ data: sample.data });
dragComplete(sample);
console.log({ data: sample.data });
.as-console-wrapper { min-height: 100%!important; top: 0; }

How to get nodes of Json using jquery?

I have a JSON and i want to get its node under a Node, but net getting how cani get it: Here is the JSON:
{
"price": {
"VPO": 125,
"MSRP": 129.99,
"ONSALE": 99.97,
"a_bucks": 3.75
},
"short_info": {
"product_name": "MARMOT PRECIP JACKET",
"category": "WOMEN'S",
"weight": {
"lbs": 0.6,
"kg": 0.27
},
"SKU": "KNXSU921",
"part_info": "#46200",
"rating": 4,
"out_of_stock": false
},
"product_variants": {
"XS": {
"Arctic Navy": {
"InStock": true,
"Colorcode": "HMN",
"InStore": {
"NANAIMO": {
"value": "true",
"code": "154"
}
}
},
"Black": {
"InStock": true,
"Colorcode": "HMN",
"InStore": {
"NANAIMO": {
"value": "true",
"code": "154"
}
}
},
"Blue Sea": {
"InStock": true,
"Colorcode": "HMN",
"InStore": {
"NANAIMO": {
"value": "true",
"code": "154"
}
}
},
}
}
}
I want to get Elements's (Nodes) name under XS, i.e. "Arctic Navy", "Black", "Blue Sea" etc.
I have used following code:
$.each(dataObj.product_variants.XS, function (i, item) {
alert(item)
});
But not getting how can i get the required output. Please help.
Thanks in advance.
You don't need jQuery for this. You can use normal JavaScript:
Object.keys(dataObj.product_variants.XS)
This will return an array of the keys. e.g.
[ "Arctic Navy", "Black", "Blue Sea" ]
You can try
$.each(dataObj.product_variants.XS, function (i, item) {
alert(i)
});
It can be achieved through javascript also
for(var i in dataObj.product_variants.XS) {
alert(i)
});
If your dataObj.product_variants.XS would have been array, i would have been index of the element.
Try the following:
Use Object.keys() to get the keys of a object
var keys = Object.keys(dataObj.product_variants.XS);
https://jsfiddle.net/zeoj9xd8/
try
$.each(Object.keys(obj.product_variants.XS), function (i, item) {
alert(item)
});
https://jsfiddle.net/qejss4yj/

Google Chrome Apps: chrome.storage.local

I am having a struggle finding out why the following is happening in a application i'm developing:
So i read a JSON file where i want to read and save his content on localStorage, which in a chrome app is chrome.storage.local
So i get the following from a json file:
{
"schedule": {
"id": "416a18d6-7e42-4f8a-ac24-e902abe76f39",
"name": "blabla",
"updatedOn": "2013-09-08T16:34:41.000Z",
"etag": "esxrdctfvygbuhnij5464df7g8hu",
"applications": [
{
"id": "app001",
"type": "text/html",
"src": "http://www.google.com"
},
{
"id": "app002",
"type": "text/html",
"src": "http://www.stackoverflow.com"
}
],
"normalContent": [
{
"layout_id": "layout001",
"layout_name": "layout1",
"layout_dur": "indefinite",
"regions": [
{
"region_id": "region001",
"region_name": "regiao1",
"left": "0",
"top": "0",
"width": "0.5",
"height": "1",
"minWidth": "0",
"minHeight": "0",
"scheduleItem": "container",
"limitCycle": "1",
"selector": "seq",
"containerList": [
{
"cid": "app001",
"dur": "25"
},
{
"cid": "app002",
"dur": "15"
}
]
},
{
"region_id": "region002",
"region_name": "regiao2",
"left": "0.5",
"top": "0",
"width": "0.5",
"height": "1",
"minWidth": "0",
"minHeight": "0",
"scheduleItem": "container",
"limitCycle": "1",
"selector": "seq",
"containerList": [
{
"cid": "app002",
"dur": "15"
},
{
"cid": "app001",
"dur": "15"
}
]
}
]
}
]
}
}
So i get this and then i save the content in storage using:
chrome.storage.local.set({playerSchedule:this.schedule}, function(){
console.log('saved!')
});
Later on when i read the content stored using:
chrome.storage.local.get(["playerSchedule", "playerScheduleType"], function (res) {
self.currentSchedule = res.playerSchedule;
self.scheduleType = res.playerScheduleType;
});
This is what i get:
{
"schedule": {
"applications": [
{
"id": "app001",
"type": "text/html",
"src": "http://www.google.com"
},
{
"id": "app002",
"type": "text/html",
"src": "http://www.stackoverflow.com"
}
],
"etag": "esxrdctfvygbuhnij5464df7g8hu",
"id": "416a18d6-7e42-4f8a-ac24-e902abe76f39",
"name": "blabla",
"normalContent": [
{
"layout_dur": "indefinite",
"layout_id": "layout001",
"layout_name": "layout1",
"regions": [
{
...
"containerList": [
]
},
{
...
"containerList": [
]
}
]
}
],
"updatedOn": "2013-09-08T16:34:41.000Z"
}
}
As you can observe, the content i read comes in alphabetic order and the content in containerList is empty. Any reason why this is happening? I solved this by converting the object to string and storing it, but i wonder why saving as object i get that from reading as an object or is there something i am missing?
Thanks in advance.
This is probably http://code.google.com/p/chromium/issues/detail?id=277647. Fix is in the works for Chrome 31.

Categories