Access array inside JSON object using Axios Vue JS - javascript

I need to access arrays inside JSON object and save into different arrays. I tried few ways but no luck.
I could get all other values without any problem but when it comes to arrays I couldn't retrieve those.
I feel the way I try to access arrays inside JSON object might be wrong and but I couldn't figure it out
Here is JSON object
{
"packId":51,
"shortCode":"TTY",
"packDescription":"TTY Des",
"startDate":"2020-09-01",
"endDate":"2020-09-08",
"validityValue":30,
"validityType":"Hours",
"expiryAction":true,
"expirySMS":64,
"activationSMS":64,
"deactivationSMS":64,
"subscriptionSMS":0,
"deactivationAction":true,
"deactivationShortCode":"DEACT TTY",
"deprovisionOnExpiry":true,
"deleteByPackType":true,
"packType":{
"packTypeId":2,
"name":"Facebook"
},
"timeBands":[
{
"timeBandId":1,
"start":"8:00",
"end":"23:00",
"timeBand":"8:00-23:00"
},
{
"timeBandId":2,
"start":"8:00",
"end":"20:00",
"timeBand":"8:00-20:00"
}
],
"activationTypes":[
{
"activationTypeId":1,
"name":"SMS"
},
{
"activationTypeId":2,
"name":"Web"
}
],
"channels":[
{
"channelId":1,
"name":"hShenid"
},
{
"channelId":2,
"name":"Genesis"
}
],
"users":[
]
}
Axios Call
getPackById(id)
{
return axios.get(`${API_URL}/pack/get/${id}`);
}
refreshPack()
{
PackComposeDataService.getPackById(this.id).then((res)=>
{
//I can access these values without any problem
this.deleteByPackType= res.data.deleteByPackType,
this.packTypeValues=res.data.packType,
this.shortCode= res.data.shortCode,
this.packDescription= res.data.packDescription,
this.startDate= res.data.startDate,
this.endDate= res.data.endDate,
this.subscriptionSMS= res.data.subsNotificationValues["id"],
this.validityValue= res.data.validityValue,
this.validityType= res.data.validityType,
this.actionOnExpiry= res.data.expiryAction,
this.expirySMS= res.data.expiryNotificationValues,
this.activationSMS= res.data.activationNotificationValues,
this.deactivationAction= res.data.deactivationAction,
this.deactivationShortCode= res.data.deactivationShortCode,
this.deactivationSMS= res.data.deactivationNotificationValues,
this.deprovisionOnExpiry= res.data.deprovisionOnExpiry,
//I need to get these arrays
this.timeBandValues= res.data.timeBands,
this.activationTypes= res.data.activationTypes,
this.channels= res.data.channels,
this.users= res.data.users
});

I understand you want to take only the timeBand string of each of the arrays (or the activationType, eventually).
If that's the case, you may want to map to convert each object in the array to a simple string:
// ...
this.timeBandValues = res.data.timeBands.map(o => o.timeBand) // you're going to get ["8:00-23:00", "8:00-20:00"]
// ...

Related

Rendering Mongo document values in Pug template w/ Express

I'm retrieving documents from Mongo Atlas using the new data API like this :
axios(config)
.then(function (response) {
console.log(response.data);
res.render('profile', {
snippets: response.data,
})
.catch(function (error) {
console.log(error);
});
};
My console.log(response.data) shows the documents correctly like this :
documents: [
{
_id: '6245b82edde6452fece5d27d',
snippet: '<p>This is a test post in <strong>bold, </strong>in <em>italic, </em>in <span style="text-decoration: underline;">underline,</span> and with a link</p>'
},
{
_id: '6245b8fbe9d255ab42528197',
snippet: '<p>This is a test post in <strong>bold, </strong>in <em>italic, </em>in <span style="text-decoration: underline;">underline,</span> and with a link. A second time!</p>'
}
]
}
Then I followed this answer to try render a simple list of these of the snippet values in a table :
table
each snippet in snippets
tr#snippet_list_item
td #{snippet._id}
td #{snippet.snippet}
But I get
snippets include [object Object],[object Object]
rendered on the front end instead of the values.
What am I missing? My thinking was... pass the objects, iterate through, access the values for each. But I'm obviously not doing something right.
Okay so for people coming to this whilst still learning...
If you ever get this problem, where you are trying to access values inside an array of objects and are getting 'Object Object', make sure to look at the structure of the data you are getting.
See below
documents: [
{
_id: '6245b82edde6452fece5d27d',
snippet: '<p>This is a test post in <strong>bold, </strong>in <em>italic, </em>in <span style="text-decoration: underline;">underline,</span> and with a link</p>'
},
{
_id: '6245b8fbe9d255ab42528197',
snippet: '<p>This is a test post in <strong>bold, </strong>in <em>italic, </em>in <span style="text-decoration: underline;">underline,</span> and with a link. A second time!</p>'
}
]
}
My data is structured like this :
'documents'[
{document 1}
{document 2}
]
Each {document} is an object. But they are all inside an array of objects, which in my case is 'documents'. You can see this by the [] square brackets that the {documents} are contained inside.
So when accessing the values, you first need to access the array by response.data.{$name_of_array}, THEN, you can use dot notation to access the values
so to access the values, you'd do something like :
response.data.{$name_of_array}.{$name_of_value_name}
if accessing all of these, you'll need to iterate through them, if accessing just 1, you can use it's position in the index like this :
response.data.{$name_of_array}[$index_number].{$name_of_value_name}
Hope this helps someone!

finding nested object value in java script

JSON file from URL
{
"1": [
{
"actions": ["OUTPUT:2" ],
"idle_timeout": 0,
"cookie": 0,
"packet_count": 2,
"hard_timeout": 0
}
}
JavaScript
function myFunction() {
//alert("INTo function");
$.ajax({
url: "http://127.0.0.1:3000/flow",
cache: false,
success: function(data) {
$("#flow").append(data["1"].actions.OUTPUT[i]);
$("#flow").append(data["1"].idle_timeout);
$("#flow").append(data["1"].cookie);
$("#flow").append(data["1"].packet_count);
$("#flow").append(data["1"].hard_timeout);
}
});
}
This is the JavaScript code which I have used it, to find values of the object inside the nested JSON response coming from a URL.
Your sample does not look like valid json. Since the value of "1" is an array, you should try to access it via the index. e.g.$("#flow").append(data["1"][0].idle_timeout)
The code used to find the values inside the nested JSON object is actually incorrect.
You must use data["1"][0].actions[0].OUTPUT to retrieve the value 2.

Sequelize: .createAssociation() or .setAssociation doesn't update the original object with created data

I've been stuck on this for a while. Take the following code as an example:
models.Summoner.findOne({
include: [{ model: models.RankedStats, as: 'SummonerRankedStats', required: true }],
where: { summonerId: summonerId, server: server }
}).then(function(summoner) {
models.RankedStats.create({
totalWins: 0,
totalLosses: 0
}).then(function(rankedStats) {
summoner.setSummonerRankedStats(rankedStats).then(function() {
console.log(summoner.SummonerRankedStats)
//This outputs undefined
summoner.getSummonerRankedStats().then(function(srs) {
console.log(srs)
//This outputs the RankedStats that were just created
})
models.Summoner.findOne({
include: [{ model: models.RankedStats, as: 'SummonerRankedStats', required: true }],
where: { summonerId: summonerId, server: server }
}).then(function(summoner) {
console.log(summoner.SummonerRankedStats)
//This outputs the SummonerRankedStats object
})
})
})
})
So, to put it simply... If I have a Summoner (var summoner) and perform a .setAssociation() or .createAssociation() on it, and then log summoner, the data created isn't there. If I fetch it again from the database (with .getAssociation() or by searching for that Summoner again) I can access it, but I was hoping to avoid that extra DB call.
Is there a way to add this information to the original object when using .create() or .set()? It can be achieved by doing something like:
summoner.dataValues.SummonerRankedStats = rankedStats
But that seems somewhat hacky :)
Is there a correct way to do it, or does it even make any sense?
Thanks in advance!

Breeze and Knockout not binding correctly

I was trying a sample using breeze and knockout
manager.executeQuery(query).then(function(result){
console.log(result);
ko.applyBindings(result);
}).fail(function(e) {
console.log(e);
alert(e);
});
While printing in the console. I'm getting two objects in the path data.XHR.result.responseJSON and two objects in data.results
But in the view created as a result of knockout binding I'm getting the second set of value populated two times. (I have two set of values in the db)
NOTE: This code is working if I havent defined any metadata. Issue is in the scenario where I use metadata
metadata
var sample=sample||{};sample.metadata=
{
"dataServices":[
{
"serviceName":"/sample",
"hasServerMetadata":true,
"jsonResultsAdapter":"webApi_default",
"useJsonp":false
}
],
"structuralTypes":[
{
"shortName":"Employee",
"autoGeneratedKeyType":"None",
"defaultResourceName":"Employee",
"dataProperties":[
{
"name":"id",
"dataType":"MongoObjectId",
"isNullable":false,
"defaultValue":"",
"isPartOfKey":true,
"validators":[
{
"name":"required"
}
]
},
{
"name":"name",
"dataType":"String",
"maxLength":100,
"validators":[
{
"maxLength":100,
"name":"maxLength"
}
]
},
{
"name":"age",
"dataType":"String",
"maxLength":100,
"validators":[
{
"maxLength":100,
"name":"maxLength"
}
]
}
]
}
],
"resourceEntityTypeMap":{
"Employee":"Employee"
}
};
Make sure that you have a primary key that is defined in your model and coming across the wire. If you leave those values as null they will overwrite each other when breeze adds them to the cache and sees the keys are the same.

How do I access JSON elements through javascript?

The JSON file I have is following:
{
"root": {
"Quizsize": null,
"{urn:abc.com/xmlns/mona/page}page": [
{
"#xid": "page1623",
"#title": "Quiz Landing Page",
"{urn:abc.com/xmlns/mona/page}comment": null,
"{urn:abc.com/xmlns/mona/page}skills": null,
"{urn:abc.com/xmlns/mona/page}info": {
"{urn:abc.com/xmlns/mona/common}property": {
"#name": "quiz_landing",
"#value": "true"
}
}
}
]
}
}
}
I am loading this JSON file using :
var jsondata = eval("("+chapterRequest.responseText+")") ;
Root = jsondata.root
Now I want to access #xid which is "page1623 and #name which is "quiz_landing". I dont know how to do this,Please help.
Thanks
JSON.parse(x) is better than eval(x), for one. It is not supported natively by some browsers though. If you want to access #xid, "urn:abc.com/xmlns/mona/page}page" points to an array whose first element is an object.
So use Root["{urn:abc.com/xmlns/mona/page}page"][0]["#xid"]. Or mix bracket and dot notation. Your choice, really.
When the key isn't a valid identifier, you use object['key'] instead of object.key, so jsondata.root['{urn:abc.com/xmlns/mona/page}page'][0]['#xid'].

Categories

Resources