I want to receive the dependency string from the dataDependencyMap.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<script>
var data =
[
{
"id": 1,
"active": true,
"dependency": [
{"id": 2, "type": "critical" },
{"id": 3, "type": "moderate"}
]
},
{
"id": 2,
"active": true,
"dependency":[
{"id": 3, "type": "moderate"}
]
},
{
"id": 3,
"active": false,
"dependency":[]
}
]
// this works as it should
var dataActiveMap = new Map(data.map(obj => [obj.id, obj.active]))
data.forEach(function({id}) {
if (dataActiveMap.get(id) == true ) {
console.log(id, "active: ", true)
}
})
// HERE IS THE PROBLEM: How can I return the dependency string, like "critical" or "moderate"
var dataDependencyMap = new Map(data.map(obj => [obj.id, obj.dependency]))
data.forEach(function({id}) {
if (dataActiveMap.get(id) == true) {
console.log(id, "dependency: ", dependency.value)
}
})
</script>
</html>
There is no value property of dependency, you can pass dependency so that you can access that object like the following way:
<script>
var data =
[
{
"id": 1,
"active": true,
"dependency": [
{"id": 2, "type": "critical" },
{"id": 3, "type": "moderate"}
]
},
{
"id": 2,
"active": true,
"dependency":[
{"id": 3, "type": "moderate"}
]
},
{
"id": 3,
"active": false,
"dependency":[]
}
]
// this works as it should
var dataActiveMap = new Map(data.map(obj => [obj.id, obj.active]))
data.forEach(function({id}) {
if (dataActiveMap.get(id) == true ) {
//console.log(id, "active: ", true)
}
})
// HERE IS THE PROBLEM: How can I return the dependency string, like "critical" or "moderate"
var dataDependencyMap = data.map(({id, dependency}) => ({id, dependency}));
data.forEach(function({id, dependency}) {
if (dataActiveMap.get(id) == true) {
//console.log(id, "dependency: ", dependency);
// if you need the *type* property as comma separated string
console.log("id:", id, "and dependency:", dependency.map(({type}) => type).join(', '));
}
})
</script>
I'm not sure what the dataActiveMap constant would be used for but an alternative solution would be to use for loops. If you still need the dataActiveMap and dataDependencyMap, you can always create those arrays and use the push() method to add the values to the arrays at appropriate times in the loops. Check the solution below.
for (key in data){ // loops through the data array
// console.log(data[key])
if (data[key].active) // checks if each object's active property in data array is true
{
// console.log(data[key].dependency)
for (dependency in data[key].dependency) // loops through dependencies
{
// console.log(data[key].dependency[dependency])
for (props in data[key].dependency[dependency]) // loops through objects nested in dependencies
{
console.log(data[key].dependency[dependency].type) //prints the type property
}
}
}
}
I'm ultimately looking to create a HTML file that will accomplish the following tasks. The point is, I need it to be all inclusive in an HTML snippet/file.
Make a GET api call to a backend CMS (ie: Drupal). This api call returns the following JSON data for a specific content item:
{
"jsonapi": {
"version": "1.0",
"meta": {
"links": {
"self": {
"href": "http://jsonapi.org/format/1.0/"
}
}
}
},
"data": {
"type": "node--espot_html",
"id": "fbaab7dd-09c2-4aa0-852d-4b9462074a45",
"attributes": {
"drupal_internal__nid": 1,
"drupal_internal__vid": 11,
"langcode": "en",
"revision_timestamp": "2019-10-31T13:29:29+00:00",
"revision_log": null,
"status": true,
"title": "Razor Hero Image",
"created": "2019-10-28T16:24:20+00:00",
"changed": "2019-10-31T13:29:29+00:00",
"promote": true,
"sticky": false,
"default_langcode": true,
"revision_translation_affected": true,
"path": {
"alias": "/razor-hero",
"pid": 1,
"langcode": "en"
},
"body": {
"value": "<div class=\"jns-hero-image jns-hero-image-message-left\" id=\"hero_slideshow\"><img alt=\"Clean Shave\" data-entity-type=\"file\" data-entity-uuid=\"fbc875d0-ef17-4813-981c-22a29e42c44f\" src=\"/sites/default/files/inline-images/dont-shave-2.jpg\" />\r\n<div class=\"grid-container\">\r\n<div class=\"grid-x grid-padding-x\">\r\n<div class=\"small-12 medium-8 cell hero-message\">\r\n<div>\r\n<h1 class=\"text-hero text-hero-left\">Get a Much Better<br />\r\nShave</h1>\r\n\r\n<p>Fewer things look and feel better than a clean shave!</p>\r\n<a>SHOP NOW</a></div>\r\n</div>\r\n</div>\r\n</div>\r\n</div>\r\n",
"format": "full_html",
"processed": "<div class=\"jns-hero-image jns-hero-image-message-left\" id=\"hero_slideshow\"><img alt=\"Clean Shave\" data-entity-type=\"file\" data-entity-uuid=\"fbc875d0-ef17-4813-981c-22a29e42c44f\" src=\"/sites/default/files/inline-images/dont-shave-2.jpg\" /><div class=\"grid-container\">\n<div class=\"grid-x grid-padding-x\">\n<div class=\"small-12 medium-8 cell hero-message\">\n<div>\n<h1 class=\"text-hero text-hero-left\">Get a Much Better<br />\nShave</h1>\n\n<p>Fewer things look and feel better than a clean shave!</p>\n<a>SHOP NOW</a></div>\n</div>\n</div>\n</div>\n</div>\n",
"summary": ""
}
},
"relationships": {
"node_type": {
"data": {
"type": "node_type--node_type",
"id": "837a5cbe-f8fe-4c03-a613-2092dff1168e"
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/node_type?resourceVersion=id%3A11"
},
"related": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/node_type?resourceVersion=id%3A11"
}
}
},
"revision_uid": {
"data": {
"type": "user--user",
"id": "c0d80edb-325a-4ad7-9be3-bc9dc32ed878"
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/revision_uid?resourceVersion=id%3A11"
},
"related": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/revision_uid?resourceVersion=id%3A11"
}
}
},
"uid": {
"data": {
"type": "user--user",
"id": "c0d80edb-325a-4ad7-9be3-bc9dc32ed878"
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/uid?resourceVersion=id%3A11"
},
"related": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/uid?resourceVersion=id%3A11"
}
}
}
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45?resourceVersion=id%3A11"
}
}
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45"
}
}
}
I'm then looking for the JSON response to be parsed to extract the only the data under the "value": object.
I need to have the escape characters removed
The end result should be that the HTML (shown below) is rendered in the browser:
<div class="jns-hero-image jns-hero-image-message-left" id="hero_slideshow"><img alt="Clean Shave" data-entity-type="file" data-entity-uuid="fbc875d0-ef17-4813-981c-22a29e42c44f" src="/sites/default/files/inline-images/dont-shave-2.jpg" /><div class="grid-container"><div class="grid-x grid-padding-x"><div class="small-12 medium-8 cell hero-message"><div><h1 class="text-hero text-hero-left">Get a Much Better<br />Shave</h1><p>Fewer things look and feel better than a clean shave!</p><a>SHOP NOW</a></div></div></div></div></div>"
If processed successfully, this is what should display on the webpage:
Screenshot if image rendered via HTML
Here is the HTML I have tried. My apologies for breaking etiquette, I was not aware this would be perceived as such. In my browsers console it tells me the forEach is not a valid function or this response.
'<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ghibli App</title>
<link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet" />
<!-- <link href="style.css" rel="stylesheet" /> -->
</head>
<body>
<div id="root"></div>
<script>
const app = document.getElementById('root');
const container = document.createElement('div');
container.setAttribute('class', 'container');
app.appendChild(logo);
app.appendChild(container);
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45', true);
request.onload = function () {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
data.forEach(value => {
const card = document.createElement('div');
card.setAttribute('class', 'card');
const h1 = document.createElement('h1');
h1.textContent = valuable.title;
const p = document.createElement('p');
value.description = value.description.substring(0, 300);
p.textContent = `${value.description}...`;
container.appendChild(card);
card.appendChild(h1);
card.appendChild(p);
});
} else {
const errorMessage = document.createElement('marquee');
errorMessage.textContent = `Gah, it's not working!`;
app.appendChild(errorMessage);
}
}
request.send();
</script>
</body>
</html>'
This ended up producing the end result that I was looking to produce:
<!DOCTYPE html>
<html>
<body>
<div id="root"></div>
<script>
const app = document.getElementById('root');
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let obj = JSON.parse(this.responseText);
console.log(obj.data.attributes.body.value)
app.innerHTML = obj.data.attributes.body.value.replace('src="/sites','src="http://localhost:4700/sites');
}
};
xmlhttp.open("GET", "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45", true);
xmlhttp.send();
</script>
</body>
</html>
"questionnaire": [
{
"id": 6,
"status": "1",
"name": "Driniking water 24h",
"lang_id": 2,
"zona_id": 7,
"created_at": "2019-05-07 10:35:18",
"updated_at": "2019-06-01 10:01:08",
"questionnaire_category": 1,
"question_number": 1,
"content": "Driniking water Driniking water Driniking water Driniking water"
}
],
"next": {
"id": 7,
"status": "1",
"name": "Public Lighting",
"lang_id": 1,
"zona_id": 7,
"created_at": "2019-05-22 05:04:27",
"updated_at": "2019-06-01 10:00:37",
"questionnaire_category": 1,
"question_number": 2,
"content": "Public Lighting Public Lighting Public Lighting Public Lighting"
}
I have to concatenate the id of questionnaire with id of next, this is my url https://quiet-cove-41253.herokuapp.com/api/questionApi/1 , i don`t know how to concatenate these two id?????
var response = await fetch(`https://quiet-cove-41253.herokuapp.com/api/questionApi/1/6`+this.state.nextData.id);
state = {
data: [],
nextData: []
};
fetchData = async () => {
var response = await fetch(`https://quiet-cove-41253.herokuapp.com/api/questionApi/1/6`+this.state.nextData.id);
var json = await response.json();
this.setState({ data: json.questionnaire, nextData: json.next });
};
componentDidMount() {
this.fetchData();
}
render(){
return(
<View><Text>{this.state.data.id}</Text>
<Text>{this.state.data.name}</Text>
<Text>{this.state.data.content}</Text>
</View>
)
}
My point is that from the next id my questions will change
You can try with
var response = await fetch(`https://quiet-cove-41253.herokuapp.com/api/questionApi/1/6,${this.state.nextData.id}`);
I have modal, inside the modal there is a form when i click the submit button it will do this.
jquery code:
$('#add-new-content-form').on('submit', e => {
e.preventDefault();
//I want to add this block dates to the data
let blockdates = $("#block-dates").val();
let title = $("#card-title").val();
let catalogId = $("#catalog").val();
let categoryId = $("#category").val();
let subcategoryId = $('#subcategory').val();
let why = $("#why").val();
let description = $('#card-description').val();
let cancellationPolicy = $('#cancellation-policy').val();
let displayPrice = $('#display-price').val();
let displayDiscounted = $('#discounted-price').val();
let displayMaxPax = $('#display-maxpax').val();
let data = {
"blockDates":[
{
"description": "national araw ng mga puso day!",
"notAvailableDate": "2019-02-14 10:00:00"
},
{
"description": "chinese new year!",
"notAvailableDate": "2019-02-25 10:00:00"
}
],
"title": title,
"catalogId": catalogId,
"categoryId": categoryId,
"subcategoryId": subcategoryId,
"why": why,
"description": description,
"cancellationPolicy": cancellationPolicy,
"displayPrice": displayPrice,
"displayDiscounted": displayDiscounted,
"displayMaxPax": displayMaxPax
};
let content = ajax("api/unitContents", JSON.stringify(data), "POST");
// window.location.replace("/category");
});
Now, in the postman there is something just like this:
{
"blockDates":[
{
"description": "national araw ng mga puso day!",
"notAvailableDate": "2019-02-14 10:00:00"
},
{
"description": "chinese new year!",
"notAvailableDate": "2019-02-25 10:00:00"
}
],
"location":{
"identifier":"UBZ190asas11",
"name": "abulalas,purok 4",
"address" : "abulalas1 hagonoy bulacan",
"lat" : 12141.00,
"lng" : 123251.00
},
"units": 2,
"title": "sample unit content",
"catalogId": 6,
"categoryId": 22,
"subcategoryId": 13,
"contentOptions": [
{
"name":"bannana boat",
"maxPax":8,
"isAvailableDayTime":[
9,10,11,12,13,15,16,17,18,
33,34,35,36,37,39,38,39,40,
56,57,58,59,60,62,63,64,65,
80,81,82,83,84,86,87,88,89,
104,105,106,107,108,110,111,112,113,
128,129,130,131,132,134,135,136,137,
152,153,154,155,156,158,159,160,161
],
"inventoryNeededSet":[
{
"inventoryId": 1,
"count":1
},
{
"inventoryId": 1,
"count":2
}
],
"paxPrices": [
{
"count": 5,
"pricePerPax": 200,
"totalPrice": 1000,
"fee": 100
},
{
"count": 1,
"pricePerPax": 200,
"totalPrice": 200,
"fee": 10
}
]
},
{
"name":"bannana with island tour",
"maxPax":10,
"isAvailableDayTime":[
9,10,11,12,13,15,16,17,18,
33,34,35,36,37,39,38,39,40,
56,57,58,59,60,62,63,64,65,
80,81,82,83,84,86,87,88,89,
104,105,106,107,108,110,111,112,113,
128,129,130,131,132,134,135,136,137,
152,153,154,155,156,158,159,160,161
],
"inventoryNeededSet":[
{
"inventoryId": 1,
"count":2
},
{
"inventoryId": 1,
"count":2
}
],
"paxPrices": [
{
"count": 5,
"pricePerPax": 200,
"totalPrice": 1000,
"fee": 100
},
{
"count": 1,
"pricePerPax": 200,
"totalPrice": 200,
"fee": 10
}
]
}
],
"photos": [
"https://samplephoto1.com",
"https://samplephoto2.com",
"https://samplephoto3.com"
],
"videos": [
"https://samplevid1.com",
"https://samplevid2.com",
"https://samplevid3.com"
],
"why": "sample why",
"description": "sample desc",
"cancellationPolicy":"cancellationPolicy",
"displayPrice": 300,
"displayDiscounted": 250,
"displayMaxPax": 2
}
the thing is, I want to save the blockdate, what is the syntax of inserting the blockdates?
=======================UPDATED======================
Try this before stringifying the data variable:
data.blockdates = $("#block-dates").val();
To execute your code jQuery is needed. Try after inserting <script src='https://code.jquery.com/jquery-3.3.1.min.js'></script> before your code.
If you have let blockdates = $("#block-dates").val();
You can append blockdates into data like this
data['blockdates']=blockdates;
You may need to keep the elements in an object first. You can then add them to the array.
blockDates= [];
var description = $("#card-description").val();
var notAvailableDate = $("##block-dates").val();
var blockdate = {description, notAvailableDate};
blockDates.push(blockdate);
in this way => let content = ajax("api/unitContents", JSON.stringify(data, blockDates), "POST");
or
let data = {
"title": title,
"catalogId": catalogId,
"categoryId": categoryId,
"subcategoryId": subcategoryId,
"why": why,
"cancellationPolicy": cancellationPolicy,
"displayPrice": displayPrice,
"displayDiscounted": displayDiscounted,
"displayMaxPax": displayMaxPax,
"blockDates": blockDates
};
in this way => `let content = ajax("api/unitContents", JSON.stringify(data), "POST");`
I want to create HTML elements dynamically using JSON file.
{"myObject": {
"JAVA": {
"id": "JAVAsubj",
"path": "json/data.json"
},
"C#": {
"id": "JAVAsubj",
"path": "json/data1.json"
},
"C++": {
"id": "JAVAsubj",
"path": "json/data2.json"
}
}
}
This is my JSON file. i want to create HTML buttons dynamically. Buttons should be create like JAVA,C#,C++. if i add something next to C++ then that button should get created dynamically
You can try something like this FIDDLE
however, i changed the myObject to an array of json objects as follows:
var jsonObj = {"myObject":
[
{
title: 'JAVA',
id: "JAVAsubj",
path: "json/data.json"
},
{
title: "C#",
id: "JAVAsubj",
path: "json/data1.json"
},
{
title: "C++",
id: "JAVAsubj",
path: "json/data2.json"
}
]
}
var count = Object.keys(jsonObj.myObject).length;
var container= document.getElementById('buttons'); // reference to containing elm
for(var i=0;i<count;i++){
var obj= jsonObj.myObject[i];
var button = "<input type='button' value="+obj.title+"></input>"
container.innerHTML+=button;
}
First thing you need to do that get your JSON into js object :
var myJSON= {"myObject": {
"JAVA": {
"id": "JAVAsubj",
"path": "json/data.json"
},
"C#": {
"id": "JAVAsubj",
"path": "json/data1.json"
},
"C++": {
"id": "JAVAsubj",
"path": "json/data2.json"
}
}
}
now get the value of your object into dictionary like below :
var dctLanguages = myJSON["myObject"];
now to render buttons dynamically, just do this :
var strHTML = '';
for (var key in dctLanguages)
{
var language = dctLanguages[key];
strHTML += '<input type="button" id="'+language.id+'" value="'+key+'"/>';
}
and append this HTML into your container div as follows :
$(strHTML).appendTo("#container");
Hope this will work for you..
const info = [
{
"id": 1,
"img": "a.jpg",
"name": "Avinash Mehta",
"desc": "I am Web Developer"
},
{
"id": 2,
"img": "c.jpg",
"name": "Avinash",
"desc": "I am Web"
},
{
"id": 3,
"img": "b.jpg",
"name": "Mehta",
"desc": "I am Developer"
},
]
const main = document.querySelector(".main");
window.addEventListener("DOMContentLoaded", function(){
let displayInfo = info.map(function(profile){
return` <div class="profile">
<img src="${profile.img}" alt="">
<h2>${profile.name}</h2>
<p>${profile.desc}</p>
</div>`
});
displayInfo = displayInfo.join("");
main.innerHTML = displayInfo
})
This shoule help you
const info = [
{
"id": 1,
"img": "a.jpg",
"name": "Avinash Mehta",
"desc": "I am Web Developer"
},
{
"id": 2,
"img": "c.jpg",
"name": "Avinash",
"desc": "I am Web"
},
{
"id": 3,
"img": "b.jpg",
"name": "Mehta",
"desc": "I am Developer"
},
]
const main = document.querySelector(".main");
window.addEventListener("DOMContentLoaded", function(){
let displayInfo = info.map(function(profile){
return` <div class="profile">
<img src="${profile.img}" alt="">
<h2>${profile.name}</h2>
<p>${profile.desc}</p>
</div>`
});
displayInfo = displayInfo.join("");
main.innerHTML = displayInfo
})