How do I display json data with keys inside key in JavaScript? - javascript

I get data from an api, and this data contains one key, that last contains multiple keys, This is my example :
{
"status": 0,
"location": "Casablanca [Doukkala-Abda;Morocco]",
"day": {
"1": {
"date": "20200807",
"name": "Friday",
"month": "", ...
The parent key is the day
The child keys are 1, 2, 3 ...etc, they contains data
I tried to use console.log(data['day']['1']) and console.log(data.day['1']) but I got this error :
Cannot read property '1' of undefined
How do I read this properly ?

Just use the array form when the index is an interger, such as:
let data = {
"day": {
"1": {
"date" : "20200807"
}
}
}
console.log("data:", data);
console.log('data.day["1"]:', data.day["1"]);
console.log('data.day["1"].date:', data.day["1"].date);

You might want to remove the quotes like: data.day[1] instead of data.day['1']
var data =
{
"status": 0,
"location": "Casablanca [Doukkala-Abda;Morocco]",
"day": {
"1": {
"date": "20200807",
"name": "Friday",
"month": ""
},
"2": {
"date": "20200801",
"name": "test",
"month": ""
}
}
}
console.log(data.day[1]);

I assume the issue is that you need to parse your API response with JSON.parse() first, like:
let rawDataFromApi = '{"status":0,"location":"Casablanca [Doukkala-Abda;Morocco]","day":{"1":{"date":"20200807","name":"Friday","month":""}}}'
let data = JSON.parse(rawDataFromApi)
console.log(data['day']['1'])

. operator can be used to get the data.the data is a object so that [] will not be a good idea.
use day.1.date to get the data

Try this.
let data = {
"day": {
"1": {
"date" : "202008071"
}
}
}
let data2 = {
"day": {
"2": {
"date" : "202008072"
}
}
}
let data3 = {
"day": {
"third": {
"date" : "202008073"
}
}
}
console.log(data.day["1"].date);
console.log(data2.day["2"].date);
console.log(data3.day["third"].date);

Related

Compare two json files and add number to object if object with same value is still there

Lets say i have 2 Json responses from a server, one of which is 30 seconds older that the new one. How would i be able to check if an object is still inside the response and after testing if it is still there update an object in another json file to add +1 to the number of that object.
(an example because i can´t explain)
JSON coming in
"names and id´s in json changed"
{
"description": "Insert description here;",
"favicon": null,
"latency": 78.085,
"players": {
"max": 20,
"online": 3,
"sample": [
{
"id": "07bda75d-d8d2-4108-94a7-ba2c09127nsj",
"name": "oajhebskaa"
},
{
"id": "8d8aac43-112b-402b-8771-67b49183lazf",
"name": "jahebianl"
},
{
"id": "67d8a66b-ce37-439f-9020-e6de827dn2o9",
"name": "ffwqehas"
}
]
},
"version": {
"name": "Paper 1.16.4",
"protocol": 754
}
}
After cutting out wanted values it looks like this :
[
'07bda75d-d8d2-4108-94a7-ba2c09127nsj',
'8d8aac43-112b-402b-8771-67b49183lazf',
'67d8a66b-ce37-439f-9020-e6de827dn2o9'
]
What i want to do
Now upon a new response coming in i want to update another json file which should idealy look something like this...
{
"players" : [
{ "07bda75d-d8d2-4108-94a7-ba2c09127nsj": "0" },
{ "8d8aac43-112b-402b-8771-67b49183lazf": "0" },
{ "67d8a66b-ce37-439f-9020-e6de827dn2o9": "0" }
]
}
...and add 1 to the number behind a the certain playerid.
Something like this should work.
let samplePayload = {
"description": "Insert description here;",
"favicon": null,
"latency": 78.085,
"players": {
"max": 20,
"online": 3,
"sample": [{
"id": "07bda75d-d8d2-4108-94a7-ba2c09127nsj",
"name": "oajhebskaa"
},
{
"id": "8d8aac43-112b-402b-8771-67b49183lazf",
"name": "jahebianl"
},
{
"id": "67d8a66b-ce37-439f-9020-e6de827dn2o9",
"name": "ffwqehas"
}
]
},
"version": {
"name": "Paper 1.16.4",
"protocol": 754
}
};
let previousResponseIds = [];
let trackingObj = {};
function responseMiddleware(payload) {
let responseIds = payload.players.sample.map(v => v.id);
let matches = previousResponseIds.filter(v => responseIds.find(x => x === v));
for (let i = 0; i < matches.length; i++) {
if (trackingObj.hasOwnProperty(matches[i])) trackingObj[matches[i]] += 1;
else trackingObj[matches[i]] = 0;
}
previousResponseIds = responseIds;
}
/*UI below*/
let pre = document.getElementsByTagName('pre')[0];
(function updateUI() {
pre.innerText = JSON.stringify(trackingObj, null, 1);
setTimeout(updateUI, 200);
})();
document.getElementById("AddResponse").addEventListener("click", function() {
responseMiddleware(samplePayload);
});
<strong>trackingObj:</strong>
<pre></pre>
<button id="AddResponse">Simulate Response</button>
Let's start with
{
"players" : [
{ "07bda75d-d8d2-4108-94a7-ba2c09127nsj": "0" },
{ "8d8aac43-112b-402b-8771-67b49183lazf": "0" },
{ "67d8a66b-ce37-439f-9020-e6de827dn2o9": "0" }
]
}
let mainObj = JSON.parse(response1);
let players = JSON.parse(response2);
for (let entry of mainObj.players.sample) {
if (players.players.indexOf(entry.id) > -1) {
players.players[entry.id]++;
}
}
I don't have a chance to test it right this moment, give it a shot, and it should put you on the right track.

AngularJS: Object manipulation: flattening object in js

I have an object received in response from backend, and would like to extract elements of object and attach them to scope to make it available in the View.
Following is the structure of the object:
{
"Name": {
"S": "Jon Snow"
},
"Location": {
"S": "Winterfell"
},
"Details": {
"M": {
"Parents": {
"M": {
"mother": {
"S": "Lynna Stark"
}
}
},
"Dog": {
"N": "Ghost Snow"
}
}
}
}
Since I have received it from backend, I don't know what kind of object is this, and I want to convert it to a plain JSON object which should be looking something like this:
{
"Name": "Jon Snow",
"Location": "Winterfell",
"Details": {
"Parents": {
"mother": "Lynna Stark"
},
"Dog": "Ghost Snow"
}
}
Help is appreciated, as I am a beginner in AngularJS and also It would be good if someone elaborates what kind of Object did I receive? Thanks in advance.
Update 1:
Thanks for the responses. Now I have got the idea. Now the question is how to I flatten the object by one level? And If I do flatten does it tamper the original response as it is received from the backend, it may be different every time.
const data = {
"Name": {
"S": "Jon Snow"
},
"Location": {
"S": "Winterfell"
},
"Details": {
"M": {
"Parents": {
"M": {
"mother": {
"S": "Lynna Stark"
}
}
},
"Dog": {
"N": "Ghost Snow"
}
}
}
}
const flatten = (data) =>{
if(typeof data === "string") return data;
for(let key in data){
for(let deep in data[key]){
if(deep.length === 1){
const temp = data[key]
data[key] = flatten(temp[deep])
}
}
}
return data;
}
console.log( JSON.stringify(flatten(data), null, "\t"))
JS bin

Find value of an object in json, node.js

I need a way to find the kills and deaths (etc.) of the corresponding name that is inputted, and if the name is not in the object I need it to output something too.
Something like this:
if (medic does not have(name)) return;
const kills = medic.(name).kills
Sample JSON:
{
"assault": {
"general": {
"kills": 1134,
"deaths": 1122,
"abc": "123"
},
"list": {
"A": {
"name": "name1",
"kills": 12,
"deaths": 120
},
"B": {
"name": "name2",
"kills": 23,
"deaths": 53
}
}
},
"support": {
"general": {
"kills": 123,
"deaths": 11232,
"abc": "11233"
},
"list": {
"A": {
"name": "name4",
"kills": 12,
"deaths": 120
},
"B": {
"name": "name5",
"kills": 23,
"deaths": 53
}
}
}
}
First clean your data to get a nice list of the names and info:
const listOfNames = [...Object.values(data.assault.list), ...Object.values(data.support.list)]
Then use the find method on that list to search for a name, with the backup of "Not Found" if the search returns undefined:
const search = (name) => listOfNames.find(item => item.name===name) || "Not Found"
Then you can use that search function elsewhere:
console.log(search("name2")) gives
See it in action here:
https://repl.it/#LukeStorry/62916291
Do you need assault and support to be sum up or all you need is one of those? Is your data always on the same shape? I'm going to assume that it is, and I'll provide both, the sum and the individual one:
const data = // your JSON here
const getAssaultKills = name => (data.assault.list[name] || {kills: 0}).kills
const getSupportKills = name => (data.support.list[name] || {kills: 0}).kills
const getTotalKills = name =>
getSupportKills(name) + getAssaultKills(name)
getTotalKills("A") // => 24
getTotalKills("C") // => 0

How can I dynamically remove a parent in JSON with JS?

With some JavaScript, how can I transform a JSON from:
{
"d": {
"__count": "13",
"results": [
{
"__metadata": {
"id": "123"
},
"COAST": "East",
"STATUS": "done",
"COLOR": "blue",
}
]
}
}
TO
{
"__count": "13",
"data": [
{
"__metadata": {
"id": "123"
},
"COAST": "East",
"STATUS": "done",
"COLOR": "blue",
}
]
}
Basically removing the extra "d" parent and renaming results to data? I am using this in the context of vue-table in VueJS.
Assumed that you have the json saved in a variable 'data':
data = data.d
data.data = data.results
delete data.results
This function will do it.
function transform(json) {
var obj = JSON.parse(json);
obj.d.data = obj.d.result;
delete obj.d.result;
return JSON.stringify(obj.d);
}
One solution is to unserialize your JSON to have an object (JSON.parse()). Then to serialize only what you need (JSON.stringify()).
You can use a loop.
var res = [];
for(var k in jsonData){
res.push(jsonData[k]);
}
var jsonData = {
"d": {
"__count": "13",
"results": [
{
"__metadata": {
"id": "123"
},
"COAST": "East",
"STATUS": "done",
"COLOR": "blue",
}
]
}
};
console.log(jsonData);
var res = [];
for(var k in jsonData){
res.push(jsonData[k]);
}
console.log("result:");
console.log(res);

searching for repeated properties in objects in an associative array

I need to find out if one user appears more than once in the associative array (and then sum the value of the same tasks). How do I do that in javaScript?
{
"Items": [
{
"Date": {
"N": "1439883817221"
},
"UserName": {
"S": "user1"
},
"task1": {
"N": "9"
}
},
{
"Date": {
"N": "1439892361108"
},
"task2": {
"N": "3"
},
"UserName": {
"S": "user2"
}
},
{
"Date": {
"N": "1439904242126"
},
"UserName": {
"S": "user1"
},
"task2": {
"N": "2"
}
}
}}
Try this:
var uniqueNames = [];
var nonUniqueNames = [];
$.each( list.Items, function(i, item ) {
if(uniqueNames.indexOf(item.UserName.S) != -1 ){
nonUniqueNames.push(item.UserName.S);
} else {
uniqueNames.push(item.UserName.S);
}
});
alert(nonUniqueNames);
https://jsfiddle.net/c2co1hck/
As for the same tasks you can figure out the same way to do it.
Please define the same tasks anyway as you have different names and values for it.
Posting some of your code would also be appreciated.
By the way you have an error in your JSON, it should end with
]} not with }}

Categories