Related
I have a JSON response with key-values like:
....
"usp-custom-90":"45.45257926613316,9.178168599999935"
....
Note usp-custom-90has dash!
I need something like (fields doens't exist, it's just an example):
data.forEach(({fields})=>{
coordsB.push(
...fields['usp-custom-90']
);
});
Where coordsB is an array defined before.
The json would be:
],
"usp-custom-90":"45.47841306255037,9.120865849999973",
"_links":{
"self":[
{
"href":"https:\/\/www.example.it\/wp-json\/wp\/v2\/posts\/128402"
}
],
"collection":[
{
"href":"https:\/\/www.example.it\/wp-json\/wp\/v2\/posts"
}
],
"about":[
I need to push the value of each "usp-custom-90"
Full code (wrong as it is using fields which doesn't exist):
fetch('https://www.example.it/wp-json/wp/v2/posts?per_page=50&status=publish')
.then(res => res.json())
.then(data =>{
var coordsB = [];
console.log(data);
data.forEach(({fields})=>{
coordsB.push(
...fields['usp-custom-90']
);
});
Based on the data sample linked in the comments, the structure is an array of objects, each object containing a usp-custom-90 property. This is a perfect situation for the map operator for arrays.
So in the above code, this one line will do it all for you. It will create the array and populate it with all the values you're looking for.
var coordsB = data.map(x=> x["usp-custom-90"])
Something along these lines would do I guess.
Object.entries(object).reduce((ac,[k,v],i,a)=>(ac.push(v['usp-custom-90']),ac),[])
Looks like from your paste bin main object is an array with objects inside which have the key you want then:
YourMainArray.reduce((ac,d,i,a)=>(ac.push(d['usp-custom-90']),ac),[])
Tested it, gives you this:
["45.45257926613316,9.178168599999935", "45.47841306255037,9.120865849999973", "9.924,-84.090", "44.948,9.039", "45.464150416139695,9.1906395499999", "45.651,11.303", "43.83734441524854,7.905822499999999", "45.05926341591318,9.3354875", "44.872988115810074,13.85009094999998", "44.97805886586813,8.895478499999967", "45.472119466144186,9.173527250000006", "45.165,9.183", "41.937,12.441", "45.464993216140186,9.147909499999969", "45.48624411615216,9.16677489999995", "45.209,9.147", "45.464993216140186,9.147909499999969", "41.848264464222716,12.665936949999946", "45.464993216140186,9.147909499999969", "45.46851557705748,9.139416449999999", "44.507,11.314", "36.731,14.873", "36.222,-121.759", "10.093,77.060", "45.454327616134165,9.175796900000023", "45.469282816142574,9.176045000000045"]
I have the following JSON data:
{"orders":[
{"id":16,"status":"completed","total":"45.00"},
{"id":17,"status":"completed","total":"55.00"}
]}
how do I transform this data to html using json2html?
${orders.0.total} works but I want it to transform all orders, not just array 0.
I have tried the solution from this answer, but it won't work.
This is what I have:
<body>
<ul id="list"></ul>
</body>
<script type="text/javascript">
//List items
var myjson = [{"orders":[
{"id":16,"status":"completed","total":"45.00"},
{"id":17,"status":"completed","total":"55.00"}
]}];
//List item transform
var orderTransform = {"tag":"div","html":"${total}"}
var transform = {"tag":"div","children":function(){
return( json2html.transform(this,orderTransform) );
}};
$(function(){
//Create the list
$('#list').json2html(myjson,transform);
});
</script>
thx
Your transform should be modified to:
var transform = {"tag":"div","children":function(){
return( json2html.transform(this.orders,orderTransform) );
}};
Note the change of this to this.orders, as the root transform references the {orders: [...]} object, so in the children function it is necesary to specify the new array that is being used as the data.
The original code passed this as the data for the children which would make json2html try to rerender the {orders: [...]} object using the orderTransform, which is incorrect, so instead it is important to explicitly specify that the data for that transform is in the orders field.
I have an data object, which contains an array within an array, I want to loop over the parent array and read out the first object of each child array.
In the example I want to read out: {"id":1}, {"id":9}, {"id":11}
var object =
{ parts: [ [{"id":1},{"id":2},{"id":3}], [{"id":9},...], [{"id":11},... ] ] }
so far I have a for each loop:
{{#each object.parts}} ... {{/each}}
In order to get the first element, you would need:
{{#each object.parts}}
{{this.[0]}}
{{/each}}
but this would just print [object object].
The second requirement - viewing it as JSON - requires a helper in your JS:
Handlebars.registerHelper('json', function(context) {
return JSON.stringify(context);
});
and then:
{{#each object.parts}}
{{json this.[0]}}
{{/each}}
I have a javascript object that contains addresses as follows
var addressList = [
{"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"},
{"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"}
]
I want to add another "address" to it so i have somthing like the following
[
{"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"},
{"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"},
{"AddressID":"10013","AddressType":"Home","AddressLine1":"5436 Bfds Road","AddressLine2":"Sherly","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"}
]
i cant figure out how to do this ?
Use Array#push to add a new object to the array:
addressList.push({"AddressID":"10013","AddressType":"Home","AddressLine1":"5436 Bfds Road","AddressLine2":"Sherly","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"});
It's not clear to me what you're encountering, but the probable problem you're running into is that the first snippet you give is a javascript Object, and the second snippet is an Array. You'd need to so something like:
var addressList = [];
addressList.push({"AddressID":"10011",...});
You could then iterate over the list using a forEach:
addressList.forEach(function(address) {
alert(address.AddressID);
doSomethingWithAddress(address);
});
You can read more about Arrays on the MDN
addressList.push({AddressID: 1234, Country: 'Foo', ...});
I'm using Handlebars templates and JSON data is already represented in [Object object], how do I parse this data outside of the Handlebars? For example, I'm trying to populate a JavaScript variable on the page through a handlebars tag, but this doesn't work.
Any suggestions? Thank you!
EDIT:
To clarify, I'm using ExpressJS w/ Handlebars for templating. In my route, I have this:
var user = {}
user = {'id' : 123, 'name' : 'First Name'}
res.render('index', {user : user});
Then in my index.hbs template, I now have a {{user}} object. I can use {{#each}} to iterate through the object just fine. However, I'm also using Backbonejs and I want to pass this data to a View, such as this:
myView = new myView({
user : {{user}}
});
The problem is that {{user}} simply shows [Object object] in the source. If I put it in console.log I get an error that says 'Unexpected Identifier'.
When outputting {{user}}, Handlebars will first retrieve the user's .toString() value. For plain Objects, the default result of this is the "[object Object]" you're seeing.
To get something more useful, you'll either want to display a specific property of the object:
{{user.id}}
{{user.name}}
Or, you can use/define a helper to format the object differently:
Handlebars.registerHelper('json', function(context) {
return JSON.stringify(context);
});
myView = new myView({
user : {{{json user}}} // note triple brackets to disable HTML encoding
});
You can simple stringify the JSON:
var user = {}
user = {'id' : 123, 'name' : 'First Name'};
// for print
user.stringify = JSON.stringify(user);
Then in template print by:
{{{user.stringify}}};
I'm using server-side templating in node-js, but this may apply client-side as well. I register Jonathan's json helper in node. In my handler, I add context (such as addressBook) via res.locals. Then I can store the context variable client-side as follows:
<script>
{{#if addressBook}}
console.log("addressBook:", {{{json addressBook}}});
window.addressBook = {{{json addressBook}}};
{{/if}}
</script>
Note the triple curlies (as pointed out by Jim Liu).
You are trying to pass templating syntax {{ }} inside a JSON object which is not valid.
You may need to do this instead:
myView = new myView({ user : user });
In the Node Router - Stringify the response object. See below line.
response.render("view", {responseObject:JSON.stringify(object)});
In HTML Script tag - user Template literals (Template strings) and use JSON.parse.
const json= `{{{responseObject}}}`;
const str = JSON.parse(json);
Worked like a charm!
You can render the keys/values of a list or object in a Handlebars template like this:
{{#each the_object}}
{{#key}}: {{this}}
{{/each}}
If you want more control over the output formatting you can write your own helper. This one has a recursive function to traverse nested objects.
Handlebars.registerHelper('objToList', function(context) {
function toList(obj, indent) {
var res=""
for (var k in obj) {
if (obj[k] instanceof Object) {
res=res+k+"\n"+toList(obj[k], (" " + indent)) ;
}
else{
res=res+indent+k+" : "+obj[k]+"\n";
}
}
return res;
}
return toList(context,"");
});
We used handlebars for email templates and this proved useful for a user like the following
{
"user": {
"id": 123,
"name": "First Name",
"account": {
"bank": "Wells Fargo",
"sort code": " 123-456"
}
}
}
To condense (what I found to be) the most helpful answers...
JSON helper for handlebars (credit):
Handlebars.registerHelper("json", function (context) {
return JSON.stringify(context);
});
JSON helper for express-handlebars (credit and I updated to newest conventions):
app.engine(
"handlebars",
exphbs.engine({
defaultLayout: "main",
helpers: {
json: function (context) {
return JSON.stringify(context);
}
}
})
);
And then on the templating side: {{json example}}
Just improving the answer from #sajjad.
Adding a 'pre' tag will make it look a lot nicer.
<pre>
{{#each the_object}}
{{#key}}: {{this}}
{{/each}}
</pre>