I am sending array of objects to print function but not working.
<script>
var items = [{
"id": "1",
"name": "rishi"
}, {
"id": "2",
"name": "xyz"
}];
var output = "<button type='button' onClick='print(" + items + ")'>Print</button>";
document.getElementsByTagName("body").innerHTML = output;
function print(data) {
alert(data);
}
</script>
<body>
</body>
<script>
var items = [{
"id": "1",
"name": "rishi"
}, {
"id": "2",
"name": "xyz"
}];
var output = "<button type='button' onClick='print(" + items + ")'>Print</button>";
document.getElementsByTagName("body").innerHTML = output;
function print(data) {
alert(data);
}
</script>
<body>
</body>
It should return array when I will click on print
getElementsByTagName returns a collection of elements, so that you should access the body element by index [0]
In order to see the content of objects in the alert try to convert them to strings using JSON.stringify
var items = [{
"id": "1",
"name": "rishi"
}, {
"id": "2",
"name": "xyz"
}];
items = JSON.stringify(items.map(JSON.stringify))
var output = "<button type='button' onClick='print(" + items + ")'>Print</button>";
document.getElementsByTagName("body")[0].innerHTML = output;
function print(data) {
alert(data);
}
<body>
</body>
Try
function print(data) {
alert(JSON.stringify(data));
}
Otherwise you get only data type shown Object in this case
What you might do is get the first item the getElementsByTagName returns using document.getElementsByTagName("body")[0]
Then call the function print passing items as the argument onClick=print(items)
var items = [{
"id": "1",
"name": "rishi"
}, {
"id": "2",
"name": "xyz"
}];
var output = "<button type='button' onClick=print(items)>Print</button>";
document.getElementsByTagName("body")[0].innerHTML = output;
function print(data) {
alert(JSON.stringify(data));
}
Your issue is with document.getElementsByTagName("body").innerHTML. .getElementsByTagName doesn't return a single element, it returns a HTMLCollection, which contains all body tags. Imagine if you passed "p" into the same method; it is possible that there are multiple p tags and thus you need to get a collection back, not just one single element.
Instead, you can use document.querySelector('body') which will return the first found element of <body>, which you can then use .innerHTML on.
Lastly, you'll need to stringify your items array such that it is preserved when you pass it into your print method
See example below:
var items = [{
"id": "1",
"name": "rishi"
}, {
"id": "2",
"name": "xyz"
}];
var output = "<button type='button' onClick='print("+ JSON.stringify(items) + ")'>Print</button>";
document.querySelector("body").innerHTML = output;
function print(data) {
console.log(data);
alert(data);
}
Related
I'm trying to create a piece of JavaScript that can read through specific parts of a linked object and place them iteratively into another piece of code which then places the code into HTML and into the front-end.
I've managed to get the fetch part working whereby it pulls in the JSON and can be read in the console, when summoned. Once the code runs, I'm able to refer to the data and bring out the whole dataset with something like:
console.log(AllOffers);
and I can drill down into something like the offerName in the JSON by using the following syntax in a variable and calling it in the console:
var OfferName = data.offersBreakdown.allOffers[0].offers[0].offerName;
However this only pulls in the first iteration of offerName because in the variable I've set it to look into the first iteration of its parent, 'offers'. What I'm looking to do is create a variable which prints all of the offerName data so that I can call on it instead of the data_test variable further down in the code, which processes the data into HTML. Sounds confusing? It is.
Ideally what I think I need is to be able to ask it to look into each child item of 'offers' (rather than just the first one) and then have it look for 'offerName'. I can't work out how one would achieve this. The best I can come up with is to remove the [0] from 'offers', but if I do that, it returns undefined as the result.
Here's my JavaScript (and a bit of jQuery):
<script>
// fetch call for the JSON data (see below)
fetch('api_url', {
headers: {
'Authorization': 'auth_token'
}
})
.then(response => response.json())
.then(function (data) {
var AllOffers = data.offersBreakdown.allOffers[0];
var AllOffers_Offers = data.offersBreakdown.allOffers[0].offers;
var OfferName = data.offersBreakdown.allOffers[0].offers[0].offerName;
var OfferImageUrl = data.offersBreakdown.allOffers[0].offers[0].imageUrl;
console.log(AllOffers);
function createCard(cardData) {
var cardTemplate = [
'<div class="card">',
'<p>My name is: ',
cardData.Offer || 'No offer',
'</p>',
'<p>My job is: ',
cardData.Img || 'No image',
'</p></div>'
];
// a jQuery node
return jQuery(cardTemplate.join(''));
}
var data_test = [
{ "Name": OfferName, "Img": OfferImageUrl },
{ "Name": OfferName, "Img": OfferImageUrl },
{ "Name": OfferName, "Img": OfferImageUrl },
];
var cards = jQuery();
// Store all the card nodes
data_test.forEach(function(item, i) {
cards = cards.add(createCard(item));
});
// Add them to the page... for instance the <body>
jQuery(function() {
jQuery('body').append(cards);
});
</script>
Here's the JSON
<script>
// the JSON
{
"offersBreakdown": {
"totalAddedOffers": 0,
"totalOffers": 2,
"totalAddedRewards": 0,
"totalRewards": 0,
"totalAddedStreakOffers": 0,
"totalStreakOffers": 0,
"allOffers": [
{
"offers": [
{
"offerName": "Offer name 1",
"imageUrl": "https://url_path_1.jpg"
},
{
"offerName": "Offer name 2",
"imageUrl": "https://url_path_2.jpg"
},
{
"offerName": "Offer name 3",
"imageUrl": "https://url_path_3.jpg"
},
{
"offerName": "Offer name 4",
"imageUrl": "https://url_path_4.jpg"
}
]
}
</script>
I'm assuming what you're looking for is a way to loop through all of the offerNames, in which case a simple for loop would suffice. Since your data includes nested arrays and objects, we need two loops, one to iterate through your allOffers array and then a nested for loops to iterate through the offers array inside of your allOffers array
var data = {
"offersBreakdown": {
"totalAddedOffers": 0,
"totalOffers": 2,
"totalAddedRewards": 0,
"totalRewards": 0,
"totalAddedStreakOffers": 0,
"totalStreakOffers": 0,
"allOffers": [{
"offers": [{
"offerName": "Offer name 1",
"imageUrl": "https://url_path_1.jpg"
}, {
"offerName": "Offer name 2",
"imageUrl": "https://url_path_2.jpg"
}, {
"offerName": "Offer name 3",
"imageUrl": "https://url_path_3.jpg"
}, {
"offerName": "Offer name 4",
"imageUrl": "https://url_path_4.jpg"
}]
}]
}
};
var allOffers = [];
var jsonObjectAllOffers = data.offersBreakdown.allOffers;
for (var i = 0; i < jsonObjectAllOffers.length; i++) {
var offers = jsonObjectAllOffers[i].offers;
for (var j = 0; j < offers.length; j++) {
var objectToAppend = {
"Name": offers[j]["offerName"],
"Img": offers[j]["imageUrl"]
};
allOffers.push(objectToAppend);
}
}
console.log(allOffers);
And now you can use your allOffers variable to loop through with the "forEach" and make into HTML
I have a sample json structure. Here I am getting all the values into alert using each loop of jquery withing success function of a ajax call. I am getting the proper value in alert, but I am getting one by one, I need to get all into a single alert may be using push or join or split which should be separated by just space, I am not getting actually what I need to do here.
Below is the code and also I have updated the code into the following plunker : http://plnkr.co/edit/KhFhW4Z3Kk4QwvRDr1pX?p=preview
html
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="col-md-3" id="leftNavBar">
</div>
<script src="script.js"></script>
script.js
$.ajax({
type: "GET",
url: '1.json',
success: function(result) {
var parents = {};
$.each(result, function(val) {
var newjoinval = result[val].name+"-"+result[val].value
alert(newjoinval);
});
}
});
1.json
[{
"name": "parent1",
"value": ["child11", "child12"]
}, {
"name": "parent2",
"value": ["child2"]
}, {
"name": "parent3",
"value": ["child3"]
}]
You are showing the alert with individual item in each iteration of result. You can generate the string in the form you want with map() and join() with space () character before showing it in the alert.
Change the success like the following:
success: function(result) {
var parents = {};
var newjoinval = result.map(p => p.name+"-"+p.value).join(' ');
alert(newjoinval);
}
Demo:
var result = [{
"name": "parent1",
"value": ["child11", "child12"]
}, {
"name": "parent2",
"value": ["child2"]
}, {
"name": "parent3",
"value": ["child3"]
}];
var newjoinval = result.map(p => p.name+"-"+p.value).join(' ');
alert(newjoinval);
I have json array data like this:
var arr= [
{
"id": 1,
"organizationName": "psda",
"Number": "12345"
},
{
"id": 2,
"organizationNameEN": "psda",
"Number": "123456"
}
]
AND after getting this data from json file i will use
var arr1=JSON.stringify(arr)
and then use
var arr2=JSON.parse(arr1)
var i=0;
while(i>=0){
var Data = $scope.documentData = {
"id":arr2[i]["id"],
"organizationNameGE":arr2[i]["organizationName"],
"Number":rawData[i]["Number"]
};
i++}
methods after that i try to get id arr2[i]["id"] and it seems to be undefined ,it throws exception like this Form failure:
Cannot read property 'id' of undefined
What should i change to make my code work?
Method 1
actually...you can't access the arr2[i].["id"] from while loop.
so create a global variable and then use it with this keyword
Method 2
if you are using angular framework.Try using with foreach loop.
var arr= [
{
"id": 1,
"organizationName": "psda",
"Number": "12345"
},
{
"id": 2,
"organizationNameEN": "psda",
"Number": "123456"
}
];
var arr1=JSON.stringify(arr);
var arr2=JSON.parse(arr1);
arr2.forEach(element =>{
alert(element.id);
});
In JS I can do this:
var a = 'name';
var obj = { name: 1 };
alert(obj[a]);
How can I get this in Dust.js? I create example, but it's broken. Please, help me fix if.
Real case for it, is render array of objects with dynamic columns.
var tpl = `{#person row=.}
{#columns}
{row[{.}]}
{#sep}, {/sep}
{/columns}<br/>
{/person}`;
var data = {
"columns": ["id", "name", "age"],
"person": [{
"id": 1,
"name": "Larry",
"age": 45
}, {
"id": 2,
"name": "Mike",
"age": 23
}]
};
var compiled = dust.compile(tpl, "intro");
dust.loadSource(compiled);
dust.render("intro", data, function(err, out) {
document.getElementById('out').innerHTML = out;
});
<script src="http://akdubya.github.io/dustjs/dist/dust-full-0.3.0.min.js"></script>
<div id="out"></div>
I need help pushing the values from a filtered json, I need this generate a nested ul list, I can not modify the json format at this point, I you check the console.log you will see the values to create the list, at this point I can't figure how to complete the 'for loop' to render the html markup needed, any help will be appreciated, this is the jsfiddle http://jsfiddle.net/43jh9hzz/, and if you check the console log you will see the values.
This is the Js:
var json='';
var property_set = new Set();
function iterate(obj, stack) {
json="<ul>";
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property], stack + '.' + property);
}
else {
// console.log(property);
property_set.add(property);
json+="<li>";
if(typeof obj[property] !== "number") {
json+="<li>"+obj[property]+"</li>";
console.log(obj[property]);
}
}
} json += "</li>";
}
}
var listEl = document.getElementById('output');
iterate(jsonObj)
And this is the json format:
var jsonObj =
{
"level_1": [
{
"level_1_name": "CiscoSingaporeEBC",
"level_2": [
{
"level_2_name": "Khoo Tech Puat",
"level_2_id": 2222,
"level_3": [
{
"name": "Boon Leong Ong",
"id": 6919
},
{
"name": "Kiat Ho",
"id": 6917
},
{
"name": "Overall Experience",
"id": 6918
}
]
}
]
},
{
"level_1_name": "CiscoLondonEBC",
"level_2": [
{
"level_2_name": "Bernard Mathews Ltd.",
"level_2_id": 2367,
"level_3": [
{
"name": "Barry Pascolutti",
"id": 7193
},
{
"name": "Kathrine Eilersten",
"id": 7194
},
{
"name": "Martin Rowley",
"id": 7189
}
]
},
{
"level_2_name": "FNHW Day 1",
"level_2_id": 5678,
"level_3": [
{
"name": "Jurgen Gosch",
"id": 7834
},
{
"name": "Overall Experience",
"id": 7835
}
]
},
{
"level_2_name": "Groupe Steria Day 1",
"level_2_id": 2789,
"level_3": [
{
"name": "Adam Philpott",
"id": 7919
},
{
"name": "Pranav Kumar",
"id": 7921
},
{
"name": "Steve Simlo",
"id": 7928
}
]
}
]
}
]
};
enter code here
I'm not sure if I am interpretting your request correctly, but I think this is what you want: http://jsfiddle.net/mooreinteractive/43jh9hzz/1/
Basically, you are calling the iterate function to run, but then that's it. The function actually needs to also return the value it generates.
I've added to the end of the function, after the for loop completes:
return json;
Do now the function returns the value it generated, but there are some other issues too. When you recursively call the iterate function again inside the iterate function, you actually want to add what it returns to the current json string housing all of your returned value.
So on that line I changed it from:
iterate(obj[property], stack + '.' + property);
to
json += iterate(obj[property], stack + '.' + property);
Now that other value will come back as well inside the main list you were creating in the first run of the function. Ok so that's pretty close, but one more small thing. I think when you added additional surrounding LI, you actually wanted to do an UL. I changed those to ULs and now I think the result is like a UL/LI list representing the text parts of the JSON object.
Again, that may not be exactly what you were after, but I think the main take away is using the function to return the value, not just generate it, then do nothing with it.