Getting value of a nested object in JSON - javascript

I want to get the req1 value in the JSON below, programatically.Here RequestTypeItem can be changed as well, so it is not fixed. Else I could have navigated it using object.subobject
I was able to navigate till slots using
var b = JSON.parse("{ .... }");
b.request.intent.slots.RequestTypeItem.value
But I can navigate further programatically.
{"request": {
"locale": "en-US",
"timestamp": "2016-09-25T00:36:14Z",
"type": {
"name": "request",
"slots": {
"RequestTypeItem": {
"name": "RequestTypeItem",
"value": "req1"
}
}
}
}
}

In your JSON your request does not have a property of intent, it does have a property type, so you then you can access the property you want with
b.request.type.slots.RequestTypeItem.value
JSFiddle: https://jsfiddle.net/9cexbn54/
Edit: After reading your question again, maybe this is what you want:
// loop through all properties on the slots object
for (var i in b.request.type.slots) {
if (b.request.type.slots.hasOwnProperty(i)) { // make sure it is a property belonging directly to slots, and not "inherited" from the prototype chain
if (b.request.type.slots[i].value) { // make sure that the sub-property of slots has a value property
document.getElementById("output").innerHTML = b.request.type.slots[i].value;
break; // break out of the loop after getting a value
}
}
}
Here I loop through all the properties on slots, checking that the property does indeed belong to slots, and that it has value property.
JSFiddle: https://jsfiddle.net/9cexbn54/1/

I had given a link which some of you found it not useful.
Here is what would get to req1:
$data=#'
[{"request": {
"locale": "en-US",
"timestamp": "2016-09-25T00:36:14Z",
"type": {
"name": "request",
"slots": {
"RequestTypeItem": {
"name": "RequestTypeItem",
"value": "req1"
}
}
}
}
}]
'#
$json=ConvertFrom-Json $data
$json.request.type.slots.RequestTypeItem.value

Related

How to access the right json value that is located through an array?

I'm currently using the fixture file to make sure it will be easier to call the right value.
cy.fixture('latestLead.json').then(function (lead) {
this.lead = lead
})
My son file is the following:
{
"status": 0,
"result": {
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "Lead",
"url": "/services/data/v51.0/sobjects/Lead/111111111"
},
"Id": "111111111",
"Name": "Andres Latest Test"
}
]
}
}
The way that I'm trying to get the right value is the following:
cy.get(".gLFyf").type(this.lead.result.records.Id)
I'm able to get totalSize or done from the result object, but I'm not able to get any other value higher than that object. How can I get the Id value from the records Array?
You can access an array item (in your case it's the object) using the index position (in your case it's zero)
cy.get(".gLFyf").type(this.lead.result.records[0].Id)
try this
cy.get(".gLFyf").type(this.lead.result.records[0].Id)

How to get another context path in factory method?

Let's imagine that we have sap.m.UploadCollection and we bind the data to this collection which is done like this:
bind: function () {
this._oUploadCollection.bindAggregation("items", {
path: "/attachments",
factory: jQuery.proxy(this._bindUploadCollectionItem, this)
});
},
The example of the binding data is here:
{
"attachments": [
{
"size": 123,
"filename": "pdf.pdf",
"id": "pdfId"
},
{
"size": 440,
"filename": "text.txt",
"id": "textId"
}
],
"source":"personWhoAddedAttachments"
}
So, in _bindUploadCollectionItem I successfully can get size, filename and id by oContext.getProperty("nameOfParameter"), but cannot get source:
_bindUploadCollectionItem: function (sID, oContext) {
return new sap.m.UploadCollectionItem({
"id": oContext.getProperty("id"),
"fileName": oContext.getProperty("filename"),
"attributes": [
{
"title": "author",
"text": oContext.getProperty("../source") // <- problem
}]
});
},
So, because I bind attachments it is kind of clear that I could not get source, but how to reach it if I need it?
It depends a little on what property of the model you want to get to. If it is really like you described it and the target property is in the /source absolute model path, then the easiest way of getting it inside the factory function is by using: oContext.getModel().getProperty("/source").
If you need something which is inside a collection (and somehow depends on the current context), you can achieve an effect similar to the .. path construct that you tried by using something along the lines:
var sPath = oContext.getPath(),
sParent = sPath.substring(0, sPath.lastIndexOf("/")),
sText = oContext.getModel().getProperty(sParent + "/source");
return new sap.m.UploadCollectionItem({
"id": oContext.getProperty("id"),
"fileName": oContext.getProperty("filename"),
"attributes": [{
"title": "author",
"text": sText
}]
});
You basically obtain the parent object path by searching for the last / inside the path. You can apply this repeatedly (or use a split, pop some elements, followed by a join) to get to the ancestors (e.g. parent of parent).

How to find JSON object contains Object or Array in Javascript?

I am working Angular js project, I am getting form server response is JSON Object. That JSON Object contains nested Objects and Arrays. for every time i need write lot coding getting the value of key
Ex:
{
"mapData": {
"data": [
{
"key": "name",
"value": "abc"
},
{
"key": "name",
"value": "bcd"
},
{
"key": "name",
"value": "vbc"
}
]
}
}
what i was tried example is so many times, it is not related above example.
for(var key in object) {
if(key=="Id"){
Id= object[key].fieldValue;
secondData.forEach(function(item){
for(var innerItem in item){
if(innerItem =="Id"){
if(Id==item[innerItem].fieldValue){
FinalData.push(item);
}
}
}
});
}
}
Is there any way generic way Instead of writing every time for for loop and For Each loop.
could you please suggest any things
Thanks in advance
mapData.data[i].key will return your key value. i is index of your data array you can easily iterate data by
for(var i =0;i<mapData.data.length;i++){}

Accessing JSON array's through object properites

Let's say I have the next JSON file:
{
"shows": [
{
"name": "House of cards",
"rating": 8
},
{
"name": "Breaking bad",
"rating": 10
}
]
}
I want to access the rating of a show, by it's name. Something like this:
var rating = data.shows["House of cards"].rating;
Is this possible? Or something similar?
Thanks a lot!
You won't have such hash-style access just by deserializing that JSON sample.
Maybe you might be able to re-formulate how the data is serialized into JSON and use object literals even for shows:
{
"shows": {
"House of cards": {
"rating": 8
}
}
}
And you can still obtain an array of show keys using Object.keys(...):
Object.keys(x.shows);
Or you can even change the structure once you deserialize that JSON:
var x = { shows: {} };
for(var index in some.shows) {
x.shows[some.shows[index].name] = { rating: some.shows[index].rating };
}
// Accessing a show
var rating = x.shows["House of cards"].rating;
I suggest you that it should be better to do this conversion and gain the benefit of accessing your shows using plain JavaScript, rather than having to iterate the whole show array to find one.
When you use object literals, you're accessing properties like a dictionary/hash table, which makes no use of any search function behind the scenes.
Update
OP has concerns about how to iterate shows once it's an associative array/object instead of regular array:
Object.keys(shows).forEach(function(showTitle) {
// Do stuff here for each iteration
});
Or...
for(var showTitle in shows) {
// Do stuff here for each iteration
}
Update 2
Here's a working sample on jsFiddle: http://jsfiddle.net/dst4U/
Try
var rating = {
"shows": [
{
"name": "House of cards",
"rating": 8
},
{
"name": "Breaking bad",
"rating": 10
}
]
};
rating.shows.forEach(findsearchkey);
function findsearchkey(element, index, array) {
if( element.name == 'House of cards' ) {
console.log( array[index].rating );
}
}
Fiddle
var data = {"shows": [{"name": "House of cards","rating": 8},{"name": "Breaking bad","rating": 10}]};
var shows = data.shows;
var showOfRatingToBeFound = "House of cards";
for(var a in shows){
if(shows[a].name == showOfRatingToBeFound){
alert("Rating Of "+ showOfRatingToBeFound+ " is " +shows[a].rating);
}
}

how to access individual elements of a javascript object literal?

I have a javascript object literal?
I access them in my webpage as
data.list[i].ger or data.list[i].eng
If I want to directly search an entry how can I directly access that entry?
or do I have to do a linear search or a binary search upon sort?
data = {
list: [
{
"ger": "A-as",
"eng": "A as"
},
{
"ger": "A-aws",
"eng": "a-was "
},
{
"ger": "we",
"eng": "cv"
},
{
"ger": "q",
"eng": "w-la-w"
},....
for e.g. if i wanted to access
"ger": "q","eng": "w-la-w"
I would acces it as data.list[4].ger
is there any way of directly accessing knowing what is the index of that entry?
I think you may be looking for JSONSelect. It makes it easy to access data in complex JSON documents, but looks like CSS.
Check out the examples, it looks pretty much like what you want to do.
For instance, to get the eng version of ger:q, you would do .ger:val("q") ~ .eng
You can download it here and use it with JSONSelect.match or JSONSelect.forEach.
If you just want to search through your array, I'd go with something like
function lookupTrans(value, fromLang, toLang) {
for (var i = 0, dataLen = data.list.length; i < dataLen; i++) {
if (data.list[i][fromLang] === value) {
return data.list[i][toLang];
// return i (if you're lookup for just the index number)
}
}
return "";
}
However, I do want to make sure you're not trying to just do one-way internationalization. If that's the case, I'd recommend just using named keys:
var i18n = {
"translation": {
"en": "translation",
"ja": "hon'yaku"
},
"list": {
"en": "list",
"ja": "risuto"
},
"example": {
"en": "example",
"ja": "rei"
},
"imbueWithConfidence": {
"en": "Let's translate!",
"ja": "Hon'yaku shimashou!"
}
};

Categories