Javascript - accessing an object with duplicate names - javascript

I have an XML file that I read in to a Javascript object. This is called jsonXML. I can see the object in its entirety in the console when I log it. It is a pretty complex object with a lot of layers and duplication.
I need to access some of these duplicate objects but I can't seem to drill down into the specifics that I need. The problem I'm having is the duplicate objects.
Here's the structure of the JS object:
ProfileGroup:
File: (there are 85 "File Objects" I need to access)
0: (I think in the tree this is the array index of the File)
Profile:
WayPt: (there are two "WayPt" objects for each file I need to access both)
0: (I think in the tree this is the array index of the WayPt)
distance
localCoords
WayPt:
1: (I think in the tree this is the array index of the WayPt)
distance
localCoords
I was using this just to try and access the objects:
console.log(jsonXML.ProfileGroup.File.Profile.WayPt);
I can get the array of files with console.log(jsonXML.ProfileGroup.File);
But I can't get individual "File" objects or anything else past that.
Any info on this issue would be helpful. Thanks!
UPDATE
Here is some stingified JSON for those who would like to see it:
"xmlns": "www.geophysical.com/DZX/1.02",
"GlobalProperties": {
"verticalUnit": "cm",
"horizontalUnit": "m",
"dielectric": "1.8000000",
"readOnly": "0",
"unitsPerMark": "100.0000000",
"unitsPerScan": "0.0200000"
},
"Macro": {
"state": "0",
"Process": [
{
"state": "0",
"BinaryData": "0&``!```$$`!C``H``````\"`#\n"
},
{
"state": "0",
"BinaryData": "L+``!```$)`!-`C,ST[\\`````````````A$$````````````````````````#\n"
},
{
"state": "0",
"BinaryData": "ME#`!```$C#`[`P````!!``\"X00``A$(`````````````````````````````\nM````````````````````````````````#$H``,A\"``#_`P``````````````\nM````````````````````````````````````````````````````````````\n/````````````````````\n"
},
{
"state": "0",
"BinaryData": "M2``!```$0``$```````#```````````````````````#`V0```#_`P``````\n;````````````````````````````````````\n"
},
{
"state": "0",
"BinaryData": "0$``!```$\"``G`0```````\"`#\n"
}
]
},
"ProfileGroup": {
"scanRange": "0,88815",
"Radan3D": {
"localMinCoords": "-0.5000000,0.0000000,0.0000000",
"localMaxCoords": "18.0000000,25.0000000,0.0000000",
"globalMinCoords": "0.0000000,0.0000000,0.0000000",
"globalMaxCoords": "0.0000000,0.0000000,0.0000000",
"localRotationAngle": "0.0000000",
"displayXDirProfs": "1",
"displayYDirProfs": "1",
"displayOtherDirProfs": "0",
"hide": "0",
"localGain": "0.0000000",
"displayOrder": "0",
"flipDataInVertDir": "0",
"flipDataInHorizDir": "0"
},
"File": [
{
"scanRange": "0,887",
"name": "HARMONY __050.DZT",
"Profile": {
"scanRange": "0,887",
"Comment": {
"scan": "0",
"description": "Data Collection Notes: "
},
"WayPt": [
{
"scan": "0",
"mark": "User",
"name": "Mark2",
"distance": "0.0000000",
"localCoords": "0.0000000,0.5000000,0.0000000"
},
{
"scan": "887",
"distance": "18",
"localCoords": "18,0.5000000,0.0000000"
}
]
}
},
{
"scanRange": "888,1785",
"name": "HARMONY __051.DZT",
"Profile": {
"scanRange": "888,1785",
"Comment": {
"scan": "888",
"description": "Data Collection Notes: "
},
"WayPt": [
{
"scan": "888",
"mark": "User",
"name": "Mark2",
"distance": "0.0000000",
"localCoords": "18.0000000,0.5208333,0.0000000"
},
{
"scan": "1785",
"distance": "17.9400000",
"localCoords": "0.0600000,0.5208333,0.0000000"
}
]
}
},
{
"scanRange": "1786,2681",
"name": "HARMONY __052.DZT",
"Profile": {
"scanRange": "1786,2681",
"Comment": {
"scan": "1786",
"description": "Data Collection Notes: "
},
"WayPt": [
{
"scan": "1786",
"mark": "User",
"name": "Mark2",
"distance": "0.0000000",
"localCoords": "-0.5000000,1.0416667,0.0000000"
},
{
"scan": "2681",
"distance": "17.9000000",
"localCoords": "17.4000000,1.0416667,0.0000000"
}
]
}
},
{
"scanRange": "2682,3574",
"name": "HARMONY __053.DZT",
"Profile": {
"scanRange": "2682,3574",
"Comment": {
"scan": "2682",
"description": "Data Collection Notes: "
},
"WayPt": [
{
"scan": "2682",
"mark": "User",
"name": "Mark2",
"distance": "0.0000000",
"localCoords": "18.0000000,1.5625000,0.0000000"
},
{
"scan": "3574",
"distance": "17.8400000",
"localCoords": "0.1600000,1.5625000,0.0000000"
}
]
}
},
{
"scanRange": "3575,4470",
"name": "HARMONY __054.DZT",
"Profile": {
"scanRange": "3575,4470",
"Comment": {
"scan": "3575",
"description": "Data Collection Notes: "
},
"WayPt": [
{
"scan": "3575",
"mark": "User",
"name": "Mark2",
"distance": "0.0000000",
"localCoords": "-0.5000000,2.0833333,0.0000000"
},
{
"scan": "4470",
"distance": "17.9000000",
"localCoords": "17.4000000,2.0833333,0.0000000"
}
]
}
},
{
"scanRange": "4471,5370",
"name": "HARMONY __055.DZT",
"Profile": {
"scanRange": "4471,5370",
"Comment": {
"scan": "4471",
"description": "Data Collection Notes: "
},
"WayPt": [
{
"scan": "4471",
"mark": "User",
"name": "Mark2",
"distance": "0.0000000",
"localCoords": "18.0000000,2.6041667,0.0000000"
},
{
"scan": "5370",
"distance": "17.9800000",
"localCoords": "0.0200000,2.6041667,0.0000000"
}
]
}
}
]
}
}
The file is very long so I truncated it at the end of a File.

I actually looked around and figured out how to do this. I found it under a different topic but figured that I might help anyone else with this specific question.
To get to these multiple array items, you have to put in the index like this:
console.log(jsonXML.ProfileGroup.File["0"].Profile.WayPt["0"].distance);
When iterating through the object, you can use this:
files=[]; //array of file names
daters=[]; //final array of arrays
tempVal =[]; //temporary array
subArray=[]; //temporary array of sub values
var filz = jsonXML.ProfileGroup.File.length;
//depending on how many files there are, find out how many
for (i=0;i<filz;i++)
{
//add each file name to an array called 'files'
files.push(jsonXML.ProfileGroup.File[i].name);
//since in my example there are two objects called WayPt
for (j=0; j<2; j++)
{
//I use an array here to make it easy to combine into the other array
tempVal.push(jsonXML.ProfileGroup.File[i].Profile.WayPt[j].distance);
//since I have a string of comma separated values, make an array of these
subArray = jsonXML.ProfileGroup.File[i].Profile.WayPt[j].localCoords.split(',');
//combine the two above arrays
arrayNew = tempVal.concat(subArray)
push this array into the final array to use later
daters.push(arrayNew);
//reset the temporary values otherwise they will keep getting larger
tempVal=[];
arrayNew=[];
subArray=[];
}
}
This is how you drill down into the object when there are multiple entries in a named field.
Hope this helps anyone else!

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.

Reverse an array of object?

How can i reverse this array using react native ? i tried myarray.reverse(); but I get below error message.
TypeError: undefined is not an object (evaluating 'myarray.reverse')
const myarray =
Array [
Object {
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": Object {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
Object {
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": Object {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]
try to remove Array and Object from the JSON. Works perfect for me.
const myarray = [{
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
{
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]
myarray.reverse()
Is the pasted code what you are actually getting back from the API?
The formatting/syntax is not correct. As others have stated you shouldn't have the 'Array' and 'Object' words inline like that. I think you're copying code from a terminal/console that added those words in.
If the response actually looks like this you won't have any problem using myaray.reverse()
const myarray = [{
"key": "-LrcB3Xcb4QuMtd20TSn",
"value": {
"question": "26",
"timestamp": 1571558541642,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
{
"key": "-LrcB3pf0DQuCr_vfP_2",
"value": {
"question": "27",
"timestamp": 1571558542861,
"user": "9jNkvzr0chgPi0SC6rXMlVWdOF12",
},
},
]

Checking a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }

How to Accessing fields from custom search results in netsuite?

In the ui, I have created a custom transaction search with vendor lines. How do I access vendor lines values? I have something like this:
var veResults = vendorSearch.run().getRange({
start: 0,
end: 50
});
for(var i = 0; i < veResults.length; i++)
{
var vendorName = veResults[i].getValue({name: 'vendorLine.entityid');
context.response.write(vendorName);
};
If I print veResults, I get the following json:
[
{
"recordType": "vendorpayment",
"id": "210",
"values": {
"employee.entityid": "",
"trandate": "5/20/2015",
"print": "Print",
"type": [
{
"value": "VendPymt",
"text": "Bill Payment"
}
],
"payrollbatch": "",
"tranid": "2009",
"entity": [
{
"value": "35",
"text": "Pacific Bell Telephone"
}
],
"account": [
{
"value": "1",
"text": "1000 Checking"
}
],
"otherrefnum": "",
"statusref": [],
"trackingnumbers": "",
"memo": "",
"currency": [
{
"value": "1",
"text": "USA"
}
],
"expectedreceiptdate": "",
"trandate_1": "5/20/2015",
"enddate": "",
"item": [],
"vendorLine.entityid": "Pacific Bell Telephone",
"vendorLine.billaddress": "Pacific Bell Telephone\nPacific Bell Payment Center\nSacramento CA 95887-0001\nUS"
}
...]
So, the value is there, how do I get it? The search object has only getValue and getText methods, none of which work in this case.
There is a syntax error with this line
var vendorName = veResults[i].getValue({'vendorLine.entityid');
It should be
var vendorName = veResults[i].getValue('vendorLine.entityid');

How do I console.log one value of this JSON Object?

I am new to javascript and to JSON, so please forgive me.
If I have the following JSON Object, how would I console.log() out the value of autonum?
{
"database": "testdb",
"table": "path",
"affectedColumns": [
{
"name": "autonum",
"charset": null,
"type": 8
},
{
"name": "TimeStamp",
"charset": null,
"type": 18,
"metadata": {
"decimals": 0
}
},
{
"name": "FilePath",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "DirPath",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "DirName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "EventName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "FileName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "FileExt",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 10
}
},
{
"name": "FileSize",
"charset": null,
"type": 3
},
{
"name": "MainFlag",
"charset": null,
"type": 1
},
{
"name": "DeleteFlag",
"charset": null,
"type": 1
},
{
"name": "Status",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 255
}
},
{
"name": "ProcessedFlag",
"charset": null,
"type": 1
}
],
"changedColumns": [],
"fields": {
"autonum": 121,
"TimeStamp": "2016-01-13T00:21:13.000Z",
"FilePath": "c:/1E0304F120151223030158001.mp4",
"DirPath": "c:\\",
"DirName": null,
"EventName": null,
"FileName": "1E0304F120151223030158001.mp4",
"FileExt": ".mp4",
"FileSize": 2218108,
"MainFlag": 0,
"DeleteFlag": 0,
"Status": null,
"ProcessedFlag": 0
}
}
Depending on which autonum you want, and assuming your variable storing the JSON is data, you'll want to do something as follows:
console.log(data.fields.autonum);
or
console.log(data.affectedColumns[0].name);
You'd use the following code, assuming the json object is called record:
console.log(record.fields.autonum);
You have two main ways of doing it. Both are correct ways. Lets say your object is named obj. Use console.log as following:
console.log(obj.fields.autonum)
console.log(obj['fields']['autonum'])
First case is easier as compare to second case.
Second case is safer as it will allow you to even take care of keys which have spaces e.g.
var my_other_object = {
'Santa Clara': 'USA',
'Toronto': 'Canada'
};
console.log(my_other_object['Santa Clara']) // Output will be 'USA'
For your understanding, in above object 'Santa Clara' and 'Toronto' are called 'keys' of my_other_object and 'USA', 'Canada' are called 'values' of those 'keys'.
So JSON object is essentially combination of key:value pairs.
P.S. Never apologize while asking a question all questions are valid but it is good to always search before asking. Still, people are always happy to help here. We all have went through same phases. :)
Lets say your object name var data, then data.fields.autonum would give us value 121
console.log(data.fields.autonum)
Just FYI:
As it is stated on MDN website:
some JavaScript is not JSON, and some JSON is not JavaScript
Just in order to improve understanding of vocabulary, 'JSON Object' is not a thing in our context ... it is
a syntax for serializing objects

Categories