How to read from json file in html page ? [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
Guys
I want to read from json file ,i create json file and use ajax to read from it.
i create Video object which contain Courses objects (title & URL)
.
i try to read title & url of HTML as Example but no data show in the HTML page .
{
"video": {
"HTML": [
{
"title": "HTML Intro",
"URL": "http://www.youtube.com/embed/dD2EISBDjWM"
},
{
"title": "Lists",
"URL": "http://www.youtube.com/embed/09oErCBjVns"
},
{
"title": "Tables",
"URL": "http://www.youtube.com/embed/wvR40su_XBM"
},
{
"title": "Links",
"URL": "http://www.youtube.com/embed/U4UHoiK6Oo4"
},
{
"title": "Images",
"URL": "http://www.youtube.com/embed/Zy4KJeVN7Gk"
}
],
"CSS": [
{
"title": "Applying Styles",
"URL": "http://www.youtube.com/embed/Wz2klMXDqF4"
},
{
"title": "Selectors",
"URL": "http://www.youtube.com/embed/6rKan6loNTw"
},
{
"title": "Box Model",
"URL": "http://www.youtube.com/embed/NR4arpSA2jI"
},
{
"title": "Positioning",
"URL": "http://www.youtube.com/embed/W5ycN9jBuBw"
}
],
"JavaScript": [
{
"title": "Introduction to JavaScript",
"URL": "http://www.youtube.com/embed/yQaAGmHNn9s"
},
{
"title": "Comments and Statements",
"URL": "http://www.youtube.com/embed/yUyJ1gcaraM"
},
{
"title": "Variables",
"URL": "http://www.youtube.com/embed/og4Zku5VVl0"
},
{
"title": "Functions",
"URL": "http://www.youtube.com/embed/5nuqALOHN1M"
},
{
"title": "Conditions",
"URL": "http://www.youtube.com/embed/5gjr15aWp24"
},
{
"title": "Objects",
"URL": "http://www.youtube.com/embed/mgwiCUpuCxA"
},
{
"title": "Arrays",
"URL": "http://www.youtube.com/embed/nEvBcwlpkBQ"
}
],
"Jquery": [
{
"title": "Introduction",
"URL": "http://www.youtube.com/embed/hMxGhHNOkCU"
},
{
"title": "Event Binding",
"URL": "http://www.youtube.com/embed/G-POtu9J-m4"
},
{
"title": "DOM Accessing",
"URL": "http://www.youtube.com/embed/LYKRkHSLE2E"
},
{
"title": "Image Slider",
"URL": "http://www.youtube.com/embed/KkzVFB3Ba_o"
}
]
}
}
i use ajax to read from it , i need to read all HTML titles and URLs . what is the wrong with this ?
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="id01"></div>
<script>
var xhr;
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('GET', 'video.json');
xhr.onreadystatechange = function ()
{
if ((xhr.readyState === 4) && (xhr.status === 200)) {
var arr = JSON.parse(xhr.responseText);
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
video[HTML][i].title +
"</td><td>" +
video[HTML][i].URL +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
}
xhr.send();
</script>
</body>
</html>

Try substituting video["HTML"][i].title where "HTML" is string for HTML at video[HTML][i].title , also arr is not an array, but an object
var out = "<table>";
for (var i = 0; i < json.video["HTML"].length; i++) {
out += "<tr><td>" +
json.video["HTML"][i].title +
"</td><td>" +
json.video["HTML"][i].URL +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
var json = {
"video": {
"HTML": [{
"title": "HTML Intro",
"URL": "http://www.youtube.com/embed/dD2EISBDjWM"
}, {
"title": "Lists",
"URL": "http://www.youtube.com/embed/09oErCBjVns"
}, {
"title": "Tables",
"URL": "http://www.youtube.com/embed/wvR40su_XBM"
}, {
"title": "Links",
"URL": "http://www.youtube.com/embed/U4UHoiK6Oo4"
},
{
"title": "Images",
"URL": "http://www.youtube.com/embed/Zy4KJeVN7Gk"
}
],
"CSS": [{
"title": "Applying Styles",
"URL": "http://www.youtube.com/embed/Wz2klMXDqF4"
}, {
"title": "Selectors",
"URL": "http://www.youtube.com/embed/6rKan6loNTw"
}, {
"title": "Box Model",
"URL": "http://www.youtube.com/embed/NR4arpSA2jI"
}, {
"title": "Positioning",
"URL": "http://www.youtube.com/embed/W5ycN9jBuBw"
}],
"JavaScript": [{
"title": "Introduction to JavaScript",
"URL": "http://www.youtube.com/embed/yQaAGmHNn9s"
}, {
"title": "Comments and Statements",
"URL": "http://www.youtube.com/embed/yUyJ1gcaraM"
}, {
"title": "Variables",
"URL": "http://www.youtube.com/embed/og4Zku5VVl0"
}, {
"title": "Functions",
"URL": "http://www.youtube.com/embed/5nuqALOHN1M"
}, {
"title": "Conditions",
"URL": "http://www.youtube.com/embed/5gjr15aWp24"
}, {
"title": "Objects",
"URL": "http://www.youtube.com/embed/mgwiCUpuCxA"
}, {
"title": "Arrays",
"URL": "http://www.youtube.com/embed/nEvBcwlpkBQ"
}],
"Jquery": [{
"title": "Introduction",
"URL": "http://www.youtube.com/embed/hMxGhHNOkCU"
}, {
"title": "Event Binding",
"URL": "http://www.youtube.com/embed/G-POtu9J-m4"
}, {
"title": "DOM Accessing",
"URL": "http://www.youtube.com/embed/LYKRkHSLE2E"
}, {
"title": "Image Slider",
"URL": "http://www.youtube.com/embed/KkzVFB3Ba_o"
}]
}
};
var out = "<table>";
for (var i = 0; i < json.video["HTML"].length; i++) {
out += "<tr><td>" +
json.video["HTML"][i].title +
"</td><td>" +
json.video["HTML"][i].URL +
"</td></tr>";
}
out += "</table>";
document.body.innerHTML = out;

This
video[HTML][i].title
Should be
video.html[i].title

Related

How to customize sort objects by property?

Starting with a given array of objects, I group those by their classification property into an object keyed by that classification. Then I print out the desired classification effect.
Now I need to sort these classifications. I want the commonly used ones to be printed first, and other classifications to be sorted alphabetically after it.
So I hope the sorting effect is as follows:
common used is the first
others are alphabetic
Here is the expected structure, the actual results in the code run
commonly-used
stackoverflow
github
movie-type
movie site
movie site2
search-type
google
wikipedia
study-type
w3c
vue
react
tool-type
remove bg
Here is my code where the grouping is done, but where I still need to add the sorting somehow:
let ary = [{
"type": "search-type",
"content": {
"title": "google",
"link": "https://",
}
}, {
"type": "study-type",
"content": {
"title": "w3c",
"link": "https://",
}
}, {
"type": "movie-type",
"content": {
"title": "movie site",
"link": "https://",
}
}, {
"type": "commonly-used",
"content": {
"title": "stackoverflow",
"link": "https://",
}
}, {
"type": "tool-type",
"content": {
"title": "remove bg",
"link": "https://www//",
}
}, {
"type": "movie-type",
"content": {
"title": "movie site2",
"link": "https://",
}
}, {
"type": "commonly-used",
"content": {
"title": "github",
"link": "https://",
}
}, {
"type": "search-type",
"content": {
"title": "wikipedia",
"link": "https://xx",
}
}, {
"type": "study-type",
"content": {
"title": "vue",
"link": "https://",
}
}, {
"type": "study-type",
"content": {
"title": "react",
"link": "https://",
}
}];
////////////////////
let tempJson = {};
ary.forEach(data => tempJson[data.type] = [])
ary.forEach(data => {
for (const key in tempJson) {
if (data.type === key) {
tempJson[key].push(data.content);
break;
}
}
})
for (const classification in tempJson) {
const wrapNode = `<div class="item-wrap">
<h3>${classification}</h3>
${(() => {
let contentWrapNode = ``;
tempJson[classification].forEach(item => {
const itemNode = `<div class="items">${item.title}</div>`;
contentWrapNode += itemNode;
})
return contentWrapNode;
})()}
</div>`;
document.querySelector('.container').innerHTML += wrapNode;
}
<div class="container"></div>
The data obtained are without order. I just classify them. How should they be sorted?
You can get a sorted version of tempJson by first extracting the key value pairs from it, and then sorting it with a callback function that deals with "commonly-used" separately:
let ary = [{
"type": "search-type",
"content": {
"title": "google",
"link": "https://",
}
}, {
"type": "study-type",
"content": {
"title": "w3c",
"link": "https://",
}
}, {
"type": "movie-type",
"content": {
"title": "movie site",
"link": "https://",
}
}, {
"type": "commonly-used",
"content": {
"title": "stackoverflow",
"link": "https://",
}
}, {
"type": "tool-type",
"content": {
"title": "remove bg",
"link": "https://www//",
}
}, {
"type": "movie-type",
"content": {
"title": "movie site2",
"link": "https://",
}
}, {
"type": "commonly-used",
"content": {
"title": "github",
"link": "https://",
}
}, {
"type": "search-type",
"content": {
"title": "wikipedia",
"link": "https://xx",
}
}, {
"type": "study-type",
"content": {
"title": "vue",
"link": "https://",
}
}, {
"type": "study-type",
"content": {
"title": "react",
"link": "https://",
}
}];
////////////////////
let tempJson = {};
ary.forEach(data => tempJson[data.type] = [])
ary.forEach(data => {
for (const key in tempJson) {
if (data.type === key) {
tempJson[key].push(data.content);
break;
}
}
})
let sorted = Object.entries(tempJson).sort(([a], [b]) =>
(a != "commonly-used") - (b != "commonly-used") ||
a.localeCompare(b)
);
for (const [classification, items] of sorted) {
const wrapNode = `<div class="item-wrap">
<h3>${classification}</h3>
${(() => {
let contentWrapNode = ``;
items.forEach(item => {
const itemNode = `<div class="items">${item.title}</div>`;
contentWrapNode += itemNode;
})
return contentWrapNode;
})()}
</div>`;
document.querySelector('.container').innerHTML += wrapNode;
}
<div class="container"></div>

My JSON data is only being populated into one ul element instead of each ul element

I have an object that stores each menu title and has the links that should go under each respective title. The problem that I am having is that all of the links are going under the first ul element and not each ul element. This(data.Items[x].Children[y].Title) should populate under each menu title. My code is below:
<html>
<body>
<footer>
<div id="footerOverlay">
<div class="container-fluid">
<div class="row">
<div class="footer-content">
<div class="footer-left">
<div class="footer-left__menu">
<div class="row">
</div>
</div>
</div>
<div class="footer-right"></div>
</div>
</div>
</div>
</div>
</footer>
<script>
data =
{
"Items": [
{
"Title": "Fitness & Training",
"Url": "/club-resources",
"Children": [
{
"Title": "Find a Club/Coach",
"Url": "/club-resources"
},
{
"Title": "Drills and Technique",
"Url": "/fitness-and-training/drills-and-technique"
},
{
"Title": "Articles and Videos",
"Url": "/fitness-and-training/articles-and-videos"
}
]
},
{
"Title": "Events",
"Url": "/events",
"Children": [
{
"Title": "Fitness Events",
"Url": "/events/fitness-events"
},
{
"Title": "Clinics",
"Url": ""
},
{
"Title": "Results",
"Url": "/comp/meets/"
}
]
},
{
"Title": "About",
"Url": "/about-us",
"Children": [
{
"Title": "About Us",
"Url": "/about-us/"
},
{
"Title": "Partners",
"Url": "sponsor-partners"
},
{
"Title": "Contact Us",
"Url": "/contact-us"
}
]
},
{
"Title": "Join",
"Url": "/register1",
"Children": [
{
"Title": "Join Now",
"Url": "/register1"
},
{
"Title": "Renew Now",
"Url": "/renew"
},
{
"Title": "Products & Discounts",
"Url": "/products-and-discounts"
}
]
}
]
};
var numOfItems = data.Items.length, footerRow = document.querySelector(".footer-left__menu > .row");
footerRow.innerHTML = "";
for(x = 0; x < numOfItems; x++)
{
footerRow.innerHTML += "<h3 class='footer-menu__header'>" + data.Items[x].Title + "</h3>";
footerRow.innerHTML += "<ul class='footer-menu__list list--nostyle'>";
footerRow.innerHTML += "</ul>";
for(y = 0; y < data.Items[x].Children.length; y++){
document.querySelector(".footer-menu__list.list--nostyle").innerHTML +=
"<li><a href=''>" + data.Items[x].Children[y].Title + "</a></li>";
}
}
</script>
</body>
</html>
You are only selecting the first ul element. Instead, use querySelectorAll and the x index to get the current one.
document.querySelectorAll(".footer-menu__list.list--nostyle")[x]...

Fetch only specific objects from JSON via javascript or jQuery

I would like to fetch only specific objects from the below JSON such as only those JSON objects which have a classDefinition = "com.sap.bpm.wfs.UserTask". Please suggest on how to do this:
var metadata = {
"contents": {
"83eaead8-cfae-459b-9bdd-8b12e32d6715": {
"classDefinition": "com.sap.bpm.wfs.StartEvent",
"id": "startevent1",
"name": "StartEvent1"
},
"13583ac9-596d-4375-b9e1-e5f6f21e829f": {
"classDefinition": "com.sap.bpm.wfs.EndEvent",
"id": "endevent1",
"name": "EndEvent1"
},
"6c2b0935-444b-4299-ac8e-92973ce93558": {
"classDefinition": "com.sap.bpm.wfs.UserTask",
"subject": "Upload document",
"description": "{context.description}",
"priority": "MEDIUM",
"isHiddenInLogForParticipant": false,
"userInterface": "sapui5://html5apps/saptest/com.sap.test",
"recipientUsers": "I311520, I310811",
"id": "usertask1",
"name": "UserTask1"
},
"6728bf81-3d4e-4ae3-a428-1700a2096d34": {
"classDefinition": "com.sap.bpm.wfs.SequenceFlow",
"id": "sequenceflow1",
"name": "SequenceFlow1",
"sourceRef": "83eaead8-cfae-459b-9bdd-8b12e32d6715",
"targetRef": "6c2b0935-444b-4299-ac8e-92973ce93558"
},
"aa99931e-2523-44c3-86b3-d522acdbde10": {
"classDefinition": "com.sap.bpm.wfs.ui.Diagram",
"symbols": {
"760f0725-3400-4d48-b082-5c69ad79d697": {},
"aa9a0d10-63be-4af8-9ac2-4d2b648a18fc": {},
"7fbd11bb-cf82-4a27-97d7-e80dda2014ee": {},
"20c66c48-6058-465e-b500-d69d6e54c028": {},
"2e8f324c-5361-4512-a09a-fc7693f206ba": {}
}
}
}
};
First, metadata.contents property should rather be an array.
If you really cannot change it to an array, then use Object.keys(metadata.contents)
For example:
Object.keys(metadata.contents)
.map(x => metadata.contents[x])
.filter(x => x.classDefinition == 'com.sap.bpm.wfs.UserTask')
var metadata = {
"contents": {
"83eaead8-cfae-459b-9bdd-8b12e32d6715": {
"classDefinition": "com.sap.bpm.wfs.StartEvent",
},
"13583ac9-596d-4375-b9e1-e5f6f21e829f": {
"classDefinition": "com.sap.bpm.wfs.EndEvent",
},
"6c2b0935-444b-4299-ac8e-92973ce93558": {
"classDefinition": "com.sap.bpm.wfs.UserTask",
"subject": "Upload document",
"description": "{context.description}",
"priority": "MEDIUM",
"isHiddenInLogForParticipant": false,
"userInterface": "sapui5://html5apps/saptest/com.sap.test",
"recipientUsers": "I311520, I310811",
"id": "usertask1",
"name": "UserTask1"
},
"6728bf81-3d4e-4ae3-a428-1700a2096d34": {
"classDefinition": "com.sap.bpm.wfs.SequenceFlow",
},
"aa99931e-2523-44c3-86b3-d522acdbde10": {
"classDefinition": "com.sap.bpm.wfs.ui.Diagram",
}
}
}
var filtered = Object.keys(metadata.contents)
.map(x => metadata.contents[x])
.filter(x => x.classDefinition == 'com.sap.bpm.wfs.UserTask')
console.log(filtered)
A simple for loop can be used to get the desired fields:
var temp = [];
for (var index in metadata.contents) {
if (metadata.contents[index].classDefinition == "com.sap.bpm.wfs.UserTask") {
temp.push(metadata.contents[index]);
}
}
Or you can do one by one
var metadata = {
"contents": {
"83eaead8-cfae-459b-9bdd-8b12e32d6715": {
"classDefinition": "com.sap.bpm.wfs.StartEvent",
"id": "startevent1",
"name": "StartEvent1"
},
"13583ac9-596d-4375-b9e1-e5f6f21e829f": {
"classDefinition": "com.sap.bpm.wfs.EndEvent",
"id": "endevent1",
"name": "EndEvent1"
},
"6c2b0935-444b-4299-ac8e-92973ce93558": {
"classDefinition": "com.sap.bpm.wfs.UserTask",
"subject": "Upload document",
"description": "{context.description}",
"priority": "MEDIUM",
"isHiddenInLogForParticipant": false,
"userInterface": "sapui5://html5apps/saptest/com.sap.test",
"recipientUsers": "I311520, I310811",
"id": "usertask1",
"name": "UserTask1"
},
"6728bf81-3d4e-4ae3-a428-1700a2096d34": {
"classDefinition": "com.sap.bpm.wfs.SequenceFlow",
"id": "sequenceflow1",
"name": "SequenceFlow1",
"sourceRef": "83eaead8-cfae-459b-9bdd-8b12e32d6715",
"targetRef": "6c2b0935-444b-4299-ac8e-92973ce93558"
},
"aa99931e-2523-44c3-86b3-d522acdbde10": {
"classDefinition": "com.sap.bpm.wfs.ui.Diagram",
"symbols": {
"760f0725-3400-4d48-b082-5c69ad79d697": {},
"aa9a0d10-63be-4af8-9ac2-4d2b648a18fc": {},
"7fbd11bb-cf82-4a27-97d7-e80dda2014ee": {},
"20c66c48-6058-465e-b500-d69d6e54c028": {},
"2e8f324c-5361-4512-a09a-fc7693f206ba": {}
}
}
}
}
var content = metadata["contents"];
var subContent = content["6c2b0935-444b-4299-ac8e-92973ce93558"];
var classDef = subContent["classDefinition"];
alert(classDef);

how to append next next level json data into tree view structure

I want to append json data to bring tree view structure. Initially I had created static tree view this is my fiddle code with json tree view: https://jsfiddle.net/ak3zLzgd/6/
Here I have challenges to append three level level json data instead of static html code.
Exactly inside retailer digital marketing > sub-ToI > semi-sub-TOI > super-sub-TOI all the thirditems json array is appending ti first value only . For more info check this fiddle: https://jsfiddle.net/ak3zLzgd/6/
var json = {
"category": [{
"title": "Customer Satisfaction",
"id": "nnanet:category/certified-pre-owned",
"items": [{
"title": "Bulletins",
"id": "nnanet:category/customer-satisfaction/bulletins",
"thirditems": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}, {
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}]
}, {
"title": "Consumer Affairs",
"id": "nnanet:category/customer-satisfaction/consumer-affairs"
}, {
"title": "Loyalty",
"id": "nnanet:category/customer-satisfaction/loyalty",
"thirditems": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}, {
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}]
}]
}, {
"title": "Retailer Digital Marketing",
"id": "nnanet:category/retailer-digital-marketing",
"items": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi",
"thirditems": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}, {
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}]
}, {
"title": "Basics",
"id": "nnanet:category/retailer-digital-marketing/reference-guide/basics"
}, {
"title": "International",
"id": "nnanet:category/retailer-digital-marketing/international"
}]
}, {
"title": "Finance Today",
"id": "nnanet:category/customer-satisfaction/bulletins/finance-today",
"items": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi",
"thirditems": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}, {
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}]
}, {
"title": "Basics",
"id": "nnanet:category/retailer-digital-marketing/reference-guide/basics"
}, {
"title": "International",
"id": "nnanet:category/retailer-digital-marketing/international"
}]
}, {
"title": "Annual",
"id": "nnanet:category/customer-satisfaction/bulletins/finance-today/revenue/annual",
"items": [{
"title": "TOI",
"id": "nnanet:category/retailer-digital-marketing/toi"
}, {
"title": "Basics",
"id": "nnanet:category/retailer-digital-marketing/reference-guide/basics"
}, {
"title": "International",
"id": "nnanet:category/retailer-digital-marketing/international"
}]
}]
};
function expander(){
var tree = document.querySelectorAll('ul.tree a:not(:last-child)');
for(var i = 0; i < tree.length; i++){
tree[i].addEventListener('click', function(e) {
var element = e.target.parentElement; //actually this is just the elem itself
var parent = element.parentElement
var opensubs = parent.querySelectorAll(':scope .open');
console.log(opensubs);
var classList = element.classList;
if(opensubs.length !=0) {
for(var i = 0; i < opensubs.length; i++){
opensubs[i].classList.remove('open');
}
}
classList.add('open');
});
}
}
$(function(){
var tree = $("ul.tree");
$.each(json.category,function(category){
var categoryValue = json.category[category];
tree.append('<li>'+categoryValue.title+'<ul></ul></li>');
var el = tree.children("li").children("ul");
$.each(categoryValue.items,function(itemId){
var item = categoryValue.items[itemId];
$(el[category]).append('<li>'+item.title+'</li>');
if(item.thirditems){
$(el[category]).children("li").append('<ul></ul>');
var el1 = el.children("li").children("ul");
$.each(item.thirditems,function(thirdItemId){
var thirdItem = item.thirditems[thirdItemId];
console.log(el1[itemId]);
$(el1[itemId]).append('<li>'+thirdItem.title+'<ul></ul></li>');
});
}
});
});
expander();
});
Output : check this fiddle : https://jsfiddle.net/ak3zLzgd/6/

How to read json array value and its child array using jquery

Hi I have a json array in the below format.
{
"data": {
"title": "MainNode"
},
"children": [{
"data": {
"title": "Firstchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "Firstchildschild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildschildsChild",
"description": "Texttexttext"
}
}]
}, {
"data": {
"title": "FirstchildsSecondchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildsSecondchildsChild",
"description": "Texttexttext"
}
}]
}]
}]
}
I have to read the array based on the title text value and list that particular data and its sub data.
For eg. If my input (title value will get from the http URL as follows) is "Firstchild/Firstchildschild/" then I have to list FirstchildschildsChild and its description.
If my input is input is /Firstchild/ then I have to list Firstchildschild & FirstchildsSecondchild data and its sub childs name.
Using jquery how can I fetch records as I mentioned above. Please advise the best way to process this json instead of using lot of loops?
Ok just for these necessities (and believe this is really a big necessity) i had invented an Object method called Object.prototype.getNestedValue() which dynamically fetches you the nested value from deeply nested Objects. All you need to provide is a string for the properties and a number for the array indices in the proper order. OK lets see...
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var JSONobj = {
"data": {
"title": "MainNode"
},
"children": [{
"data": {
"title": "Firstchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "Firstchildschild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildschildsChild",
"description": "Texttexttext"
}
}]
}, {
"data": {
"title": "FirstchildsSecondchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildsSecondchildsChild",
"description": "Texttexttext"
}
}]
}]
}]
},
value = JSONobj.getNestedValue("children",0,"children",0,"data","title");
console.log(value); // Firstchildschild
var a = "children",
b = 0,
c = "data",
d = "title";
value2 = JSONobj.getNestedValue(...[a,b,a,b,c,d])
console.log(value2); // Firstchildschild
It also has a sister called Object.prototype.setNestedValue().
var obj = jQuery.parseJSON( '
"data": {
"title": "MainNode"
},
"children": [{
"data": {
"title": "Firstchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "Firstchildschild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildschildsChild",
"description": "Texttexttext"
}
}]
}, {
"data": {
"title": "FirstchildsSecondchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildsSecondchildsChild",
"description": "Texttexttext"
}
}]
}]
}]
}' );
alert( obj.name === "data" );
You have to parse the element
obj.name === "data"
in the next link

Categories