How can I merge an Array with an object in javascript - javascript

I'm having an array of object
var todos= [
{
id: 1,
name: test,
description: test
}
]
How can I insert an object with properties stored in different variable say
var newTodos={id:2,name:test2,description:test2,purpose:NA}
so that the final arrray looks like
var todos=
[
{
id: 1,
name: test,
description: test
},
id: 2,
name: test2,
description: test2,
purpose: NA
]

var todos= [
{
id: 1,
name: test,
description: test
}
]
var newTodos={id:2,name:test2,description:test2,purpose:NA};
todos.push(newTodos);

The answer you accepted is the right answer to the wrong question.
If you really want to add the properties of newTodos (which is misnamed; it is just a single todo) then you can do what the answer says, or more easily, just do
$.extend (todos, newTodos);
_.extend (todos, newTodos);
Object.assign(todos, newTodos);
or use your other favorite property merging utility.
However, I cannot imagine what you are going to usefully do with such a mutant object, which is an array with a single element which is a todo, and now is sort of a todo itself with the todo properties directly on it.
I'm guessing that what you want to do is add another todo to your array of todos, in which case as others have suggested you can just push it.
todos.push(newTodos)
If you actually mean newTodos to be an array of todos, as its name suggests, in other words, if its format is actually
var newTodos = [ {id:2,name:test2,description:test2,purpose:NA}, ... ];
Then to add it to todos you would concatenate:
todos = todos.concat(newTodos);

This is how you do it:
for (var index in newTodos) {
todos[index] = newTodos[index];
}
You can check the values of your array like this:
for (var index in todos) {
console.log(index + ": " + todos[index]);
}
EDIT: In conform with the asked fiddle, I add the fiddle and code:
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="/js/lib/dummy.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
</style>
<script type="text/javascript">//<![CDATA[
var VanillaRunOnDomReady = function() {
var todos= [
{
id: 1,
name: 'test',
description: 'test'
}
];
var newTodos={id:2,name:'test2',description:'test2',purpose:'NA'};
for (var index in newTodos) {
todos[index] = newTodos[index];
}
var output = "";
for (var index in todos) {
if (typeof todos[index] === "object") {
output += index + ": {";
var first = true;
for (var innerIndex in todos[index]) {
if (!first) {
output += ", ";
} else {
first = false;
}
output += innerIndex + ": " + todos[index][innerIndex];
}
output += "}<br>";
} else {
output += index + ": " + todos[index] + "<br>";
}
}
document.getElementById("output").innerHTML = output;
}
var alreadyrunflag = 0;
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", function(){
alreadyrunflag=1;
VanillaRunOnDomReady();
}, false);
else if (document.all && !window.opera) {
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag = document.getElementById("contentloadtag")
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete"){
alreadyrunflag=1;
VanillaRunOnDomReady();
}
}
}
window.onload = function(){
setTimeout("if (!alreadyrunflag){VanillaRunOnDomReady}", 0);
}//]]>
</script>
</head>
<body>
<div id="output">a</div>
</body></html>

Related

Problem in executing the complete javascript

The program is not running and just showing blank window when opened in browser. Please help me found the issue with the code why it is not executing You need to create a program that will display flight information to a person. The program will continue to provide
information to the user until they indicate that they are no longer interested in searching (they will enter Q or X to stop).
The user will be prompted to enter a city to search for and you will look for any flight that starts in this city and display
the information associated with that flight.
//declare the arrays
startCity = ["Atlanta", " Cleveland", " Indianapolis", "Louisville"];
endcity = ["Cleveland", "Indianapolis", "Louisville ", "Atlanta"];
flightNumber = [RE103, RE305, RE307, RE309];
pricePerPerson = [110, 75, 90, 120];
//window onload method
window.onload = (function() {
//call function to prompt user
processPromtExecution();
//prmpt user to ask input
function processPromtExecution() {
//ask user to privide imput
var inputString = prompt("Looking for a flight? Enter the title or X to quit", "");
//check user input and if inpt is Q/q/X/x the quti with message
if (inputString == "Q" || inputString == "X" || inputString == "x" || inputString == "q") {
$("#idSpan").append("<hr /> <br />");
$("#idSpan").append("Thank you for using our flights system.");
} else {
//else search the input
for (var i = 0; i < startCity.length; i++) {
//chck input strin is part of array of book titles element or not
if (startCity[i].toLowerCase().indexOf(inputString.toLowerCase()) >= 0) {
//if matches then fetch index of other arrays
var startCity = startCity[i];
var endCity = endCity[i];
var flightNumber = flightNumber[i];
var pricePerPerson = pricePerPerson[i];
//print the message below
document.getElementById("idSpan").style.display = "block";
$("#idSpan").append("<hr />");
//set the values
$("#idSpan").append("flight Information: <br />");
$("#idSpan").append("starta: " + startCity + "<br />");
$("#idSpan").append("endCity: " + endCity + "<br />");
$("#idSpan").append("Number: " + flightNumber + "<br />");
$("#idSpan").append("Cost: " + pricePerPerson + "<br />");
//ask again
processPromtExecution();
}
}
}
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<span id="idSpan" style="display:none;">Welcome to the Javascript flightS</span>
</body>
</html>
Looks like you forgot the quote in your array with string and numbers combined in the following line:
flightNumber = [RE103, RE305, RE307, RE309];
Shouldn't it look like this:
flightNumber = ["RE103", "RE305", "RE307", "RE309"];
Consider the following.
/*
//declare the arrays
startCity = ["Atlanta", " Cleveland", " Indianapolis", "Louisville"];
endcity = ["Cleveland", "Indianapolis", "Louisville ", "Atlanta"];
flightNumber = ["RE103", "RE305", "RE307", "RE309"];
pricePerPerson = [110, 75, 90, 120];
*/
// Prepare data
var flights = [{
flightNumber: "RE103",
city: {
start: "Atlanta",
finish: "Cleveland"
},
pricePerPerson: 110
}, {
flightNumber: "RE305",
city: {
start: "Cleveland",
finish: "Indianapolis"
},
pricePerPerson: 75
}, {
flightNumber: "RE307",
city: {
start: "Indianapolis",
finish: "Louisville"
},
pricePerPerson: 90
}, {
flightNumber: "RE309",
city: {
start: "Louisville",
finish: "Atlanta"
},
pricePerPerson: 120
}];
$(function() {
// Define Functions
function getFlightDataByNumber(flightNumber, flightData) {
var results = false;
$.each(flightData, function(index, flight) {
if (flight.flightNumber.toLowerCase() == flightNumber.toLowerCase()) {
results = flight;
}
});
return results;
}
function getFlightDataByStart(cityName, flightData) {
var results = false;
$.each(flightData, function(index, flight) {
if (flight.city.start.toLowerCase() == cityName.toLowerCase()) {
results = flight;
}
});
return results;
}
function promptForFlight() {
var inputString = prompt("Looking for a flight? Enter the title or X to quit", "");
if (inputString == "Q" || inputString == "X" || inputString == "x" || inputString == "q") {
$("#idSpan").append("<hr /> <br />");
$("#idSpan").append("Thank you for using our flights system.");
} else {
var myFlight = getFlightDataByStart(inputString, flights);
if (myFlight !== false) {
$("#idSpan").show();
$("<ul>", {
class: "flightData"
}).insertAfter("#idSpan");
$("<li>").html("<label>Flight Information:</label>").appendTo(".flightData");
$("<li>").html("<label class='fixed'>Departs:</label>" + myFlight.city.start).appendTo(".flightData");
$("<li>").html("<label class='fixed'>Arrives:</label>" + myFlight.city.finish).appendTo(".flightData");
$("<li>").html("<label class='fixed'>Number:</label>" + myFlight.flightNumber).appendTo(".flightData");
$("<li>").html("<label class='fixed'>Cost:</label>$" + myFlight.pricePerPerson.toFixed(2)).appendTo(".flightData");
}
}
}
// Run Code
promptForFlight();
});
/*
//window onload method
window.onload = (function() {
//call function to prompt user
processPromtExecution();
//prmpt user to ask input
function processPromtExecution() {
//ask user to privide imput
var inputString = prompt("Looking for a flight? Enter the title or X to quit", "");
//check user input and if inpt is Q/q/X/x the quti with message
if (inputString == "Q" || inputString == "X" || inputString == "x" || inputString == "q") {
$("#idSpan").append("<hr /> <br />");
$("#idSpan").append("Thank you for using our flights system.");
} else {
//else search the input
for (var i = 0; i < startCity.length; i++) {
//chck input strin is part of array of book titles element or not
if (startCity[i].toLowerCase().indexOf(inputString.toLowerCase()) >= 0) {
//if matches then fetch index of other arrays
var startCity = startCity[i];
var endCity = endCity[i];
var flightNumber = flightNumber[i];
var pricePerPerson = pricePerPerson[i];
//print the message below
document.getElementById("idSpan").style.display = "block";
$("#idSpan").append("<hr />");
//set the values
$("#idSpan").append("flight Information: <br />");
$("#idSpan").append("starta: " + startCity + "<br />");
$("#idSpan").append("endCity: " + endCity + "<br />");
$("#idSpan").append("Number: " + flightNumber + "<br />");
$("#idSpan").append("Cost: " + pricePerPerson + "<br />");
//ask again
processPromtExecution();
}
}
}
}
});
*/
.flightData {
margin: 0;
padding: 0;
list-style: none;
}
.flightData li label {
font-weight: bold;
display: inline-block;
}
.flightData li label.fixed {
width: 120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="idSpan" style="display:none;">Welcome to the Javascript flightS</span>
Instead of using multiple unique Arrays, you may want to use an Array of Objects. This will help create a relationship between the various elements. Once you have identified the one object you need, you can easily access all the other related details.
Based on your code, you are asking the User to enter a City name, yet this is not explained well in your Prompt. You should consider clarifying the prompt better or using another Input method.
Once we have the User input, we can use the function to seek out the proper object, if we do not find it, false is returned. You have no feedback to the User if the Flight cannot be found. You might consider that scenario further.

Parse JSON foreach with JS, shows HTML list

I am currently trying to parse a JSON with JavaScript. My issue is that I'd like the output to look like this:
<li>AppName1</li>
<li>AppName2</li>
<!-- and so on... -->
However it just does not work and I don't know how to achieve that. This is the object deserialized from the JSON response:
{
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
}
This is my .js file:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("test").innerHTML = myObj.AppName;
}
};
xmlhttp.open("GET", "json.json", true);
xmlhttp.send();
This is in my HTML file
<p id="test"></p>
Any help would be appreciated as I really cannot seem to understand this a single bit. Thank you so much!
Firstly note that you can only have li elements as children of <ul> or <ol>, so the p element needs to be changed.
The AppName property is part of the objects within data, so you will need to either loop through them:
myObj.data.forEach(function(o) {
document.getElementById("test").innerHTML += '<li>' + o.AppName + '</li>';
}
Or access them, individually by index:
document.getElementById("test").innerHTML = '<li>' + myObj.data[0].AppName + '</li>'; // first item only
var myObj = {
"data": [{
"AppId": 3,
"AppName": "AnimojiStudio",
"AppSlug": "animojistudio",
"AppIcon": "https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa",
"AppVersion": "1.2.2",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "Cute Cut Pro",
"AppSlug": "cute-cut-pro",
"AppIcon": "http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa",
"AppVersion": "",
"AppSize": ""
}]
}
document.getElementById("test").innerHTML = '<li>' + myObj.data[0].AppName + '</li>';
<ul id="test"><li>
If you just want a list of the AppName properties, you could do something like the below with jQuery. See the comments in the code for details:
// Below is the JSON string from the OP's link
let json = '{"data":[{"AppId":3,"AppName":"AnimojiStudio","AppSlug":"animojistudio","AppIcon":"https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png","AppUrl":"https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa","AppVersion":"1.2.2","AppSize":"2.1"},{"AppId":2,"AppName":"Cute Cut Pro","AppSlug":"cute-cut-pro","AppIcon":"http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg","AppUrl":"https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa","AppVersion":"","AppSize":""}]}';
// Parse the JSON string into a JS object
json = JSON.parse(json);
let html = "";
// Loop over the object and append a list item for each AppName property.
$.each(json.data, function (index, item) {
html += "<li>" + item.AppName + "</li>";
});
// Append the list to the div.
$("#container").append(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div id="container"></div>
Using forEach loop and append. Inserting li inside a p tag is not a good idea even though it works. Convert the p into a ul/ol
var data = {
"data": [{
"AppId": 3,
"AppName": "AnimojiStudio",
"AppSlug": "animojistudio",
"AppIcon": "https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa",
"AppVersion": "1.2.2",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "Cute Cut Pro",
"AppSlug": "cute-cut-pro",
"AppIcon": "http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa",
"AppVersion": "",
"AppSize": ""
}]
}
data.data.forEach(e =>$('#test').append('<li>' + e.AppName + '</li>' + "<br>"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="test"></ul>
You can use map() since you have an array inside myObj. What you want to do is returning a li with AppName value
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var ul = document.getElementById("myUl");
var li = document.createElement('li');
var data = myObj.data;
data.map(app => {
li.textContent = app.AppName;
ul.appendChild(li);
})
}
};
xmlhttp.open("GET", "json.json", true);
xmlhttp.send();
You have your object, and it is parsed so let's concentrate on doing something with that object:
var myObj = {
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
};
Now we have that, let's use it in different ways. myObj contains an array called data here. That array is an array of JavaScript objects, each with properties like "AppId", "AppName" etc. which we can access either directly or through an index. So, let's put up some examples of how to do that. Comments in the code
var myObj = {
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
};
// Here I create a Bootstrap tab and contents
// call to create a new element on the DOM
function additem(item) {
let lt = $('#list-tab');
let ltc = $('#debug-tabContent');
let thing = item.name;
let thingId = "list-" + thing;
let thingTabId = thingId + "-list";
let ttab = $('<a />')
.addClass('list-group-item list-group-item-action')
.data('toggle', "list")
.prop("id", thingTabId)
.attr('role', 'tab')
.prop('href', '#' + thingId)
.html(item.name);
ttab.appendTo(lt);
let lc = $('<div />')
.addClass('tab-pane fade')
.prop("id", thingId)
.attr('role', 'tabpanel')
.text(JSON.stringify(item.obj));
// .text("test");
lc.appendTo(ltc);
}
// * cheat, put the objects in a bootstrap tab content list
additem({
name: "myObj",
obj: myObj
});
additem({
name: "myObjW",
obj: window["myObj"]
});
additem({
name: "data",
obj: myObj.data
});
additem({
name: "data0",
obj: myObj.data[0]
});
additem({
name: "AppName",
obj: myObj.data[0].AppName
});
// pure JS walk
// Here I create a LI list as a Bootstrap list group
let len = myObj.data.length;
let myP = document.getElementById("test");
let myReg = document.getElementById("mylist-reg");
let newUl = document.createElement("ul");
newUl.classList.add('list-group');
newUl.classList.add('list-group-primary');
for (var i = 0; i < len; i++) {
let newLi = document.createElement("li");
let newContent = document.createTextNode(myObj.data[i].AppName);
newLi.appendChild(newContent);
newLi.setAttribute("id", "app-" + myObj.data[i].AppId); //has to be unique
newLi.setAttribute("class", "list-group-item");
newUl.appendChild(newLi);
}
// put the list after the paragraph
document.body.insertBefore(newUl, myP);
let myLast = document.getElementById("app-2");
myLast.classList.add("active");
//activate the bootstrap tab clicks
$('#list-tab').on('click', 'a', function(e) {
e.preventDefault();
$(this).tab('show');
});
// just do it as strings
let html = "";
for (var i = 0; i < len; i++) {
let textel = "<li id='app-js-" + myObj.data[i].AppId + "'>" + myObj.data[i].AppName + "</li>";
html = html + textel;
}
myReg.innerHTML = html;
// jQuery, similar to prior
$.each(myObj.data, function(index, el) {
let textel = "<li id='app-jq-" + el.AppId + "'>" + index + ":" + el.AppName + "</li>";
$('#mylist-jq').append(textel);
});
// jQuery, similar to prior
$.each(myObj.data, function(index, el) {
let elid = 'app-jq2-' + el.AppId;
$("<li />").prop("id", elid).text(el.AppName)
.appendTo('#mylist-jq2');
});
.list-group-item {
border: 1px lime solid
}
.list-item-last {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" />
<ul id="mylist-reg"></ul>
<ul id="mylist-jq"></ul>
<ul id="mylist-jq2"></ul>
<p id="test" class="row">put stuff after here</p>
<div class="row">
<div class="col-4">
<div class="list-group" id="list-tab" role="tablist">
</div>
</div>
<div class="col-8">
<div class="tab-content" id="debug-tabContent">
<div class="tab-pane fade show active" id="list-home" role="tabpanel" aria-labelledby="list-home-list">Click a tab to see one.</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.bundle.min.js"></script>

JS Object elements printing in a web page

How can I print object array elements values in a web page using document.write ?
<!DOCTYPE html> <html> <body>
<script>
var data = [
{
"metadata" : {
"names":["times","values","types"],
"types":["time","linear","ordinal"]
},
"data": [
["1141237500000",4.216,"Global_active_power"],
["1141237560000",2.4130,"Global_active_power"],
["1141237620000",3.4230,"Global_active_power"],
["1141237680000",2.4560,"Global_active_power"],
["1141237500000",2.37130,"Voltage"],
["1141237560000",2.35840,"Voltage"],
["1141237620000",0.32690,"Voltage"],
["1141237680000",10.30980,"Voltage"],
["1141237500000",13.800,"Global_intensity"],
["1141237560000",16.400,"Global_intensity"],
["1141237620000",25.400,"Global_intensity"],
["1141237680000",13.800,"Global_intensity"],
],
}
];
document.write( data["data"] );
</script> </body> </html>
You can use JSON.stringify() to convert your object in a string form, which can the be printed on your html page with document.write.
var data = [
{
"metadata" : {
"names":["times","values","types"],
"types":["time","linear","ordinal"]
},
"data": [
["1141237500000",4.216,"Global_active_power"],
["1141237560000",2.4130,"Global_active_power"],
["1141237620000",3.4230,"Global_active_power"],
["1141237680000",2.4560,"Global_active_power"],
["1141237500000",2.37130,"Voltage"],
["1141237560000",2.35840,"Voltage"],
["1141237620000",0.32690,"Voltage"],
["1141237680000",10.30980,"Voltage"],
["1141237500000",13.800,"Global_intensity"],
["1141237560000",16.400,"Global_intensity"],
["1141237620000",25.400,"Global_intensity"],
["1141237680000",13.800,"Global_intensity"],
],
}
];
var innerDataValues = data[0].data;
// document.write( JSON.stringify(data ) );
for( var i = 0; i < innerDataValues.length; i++ )
{
var value = innerDataValues[i];
document.write( value[0] + "<br />"); // 0 for timestamp
}

How could i check if a string contains an element of an array

I have a textarea, and I need to check if this textarea.value contains a string from a string array. Every onkeyup in textarea I call this script.
I tried this code, but something went wrong. "#" is ok, but "apple" and "orange" is not. Please help me! Thanks!
var str = document.getElementById("messageArea").value;
var arr = ["#", "apple", "orange"];
for (var i = arr.length - 1; i >= 0; --i) {
if (str.indexOf(arr[i]) != -1) {
alert('contains');
} else {
alert('not contains');
}
}
Break the loop when the message contains the substring.
$("#messageArea").on("keyup",function(e){
var str = document.getElementById("messageArea").value;
var arr = ["#", "apple", "orange"];
for (var i = arr.length - 1; i >= 0; --i) {
if (str.indexOf(arr[i]) != -1) {
$('#messageBtn').prop('disabled',false);
break;
} else {
$('#messageBtn').prop('disabled',true);
}
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<textarea type="text" id="messageArea"></textarea>
<button disabled id="messageBtn">submit</button>
</body>
</html>
var str = "# apple orange"; //document.getElementById("messageArea").value;
var arr = ["#", "apple", "orange"];
str = str.trim();
var parts = str.split(" "); // split textarea string by space into another array
for (var part in parts) { // iterate one every part and check it with your arr variable
if ( arr.indexOf(parts[part]) != -1 ) {
alert("found: " + parts[part] );
} else {
alert("not contains " + parts[part]);
}
}
you will get alerts for all 3 elements in the str variable.

How to use jQuery built in functions in Mustache template

I have a mustache.js template
<script id="catagorie_list" type="text/template">
{{#rows}}<li>{{catagorie_name}}</li>{{/rows}}
</script>
in it, I want to make first letter of each {{catagorie_name}} as Capital Letter.
Example:
india --> India
australia-->Australia
Is it possible?
Use CSS, you might want to set a class like this on your a tag
.capitalize {text-transform:capitalize;}
And then your original code would look like
<script id="catagorie_list" type="text/template">
{{#rows}}<li><a class="capitalize" href="#">{{catagorie_name}}</a></li>{{/rows}}
</script>
Supposing the input object is:
var countries = {
"rows": [
{ "catagorie_name": "india" },
{ "catagorie_name": "australia" },
{ "catagorie_name": "spain" }
]
};
We append a function to it:
var func_var = {
"capitalize_name": function () {
return firstcap(this.catagorie_name);
}
};
jQuery.extend( countries, func_var ); // https://stackoverflow.com/a/10384883/1287812
The capitalization function:
function firstcap(str) { // https://stackoverflow.com/a/11370497/1287812
var len = str.length;
var re = /^\s$/;
var special = true; // signalizes whether previous char is special or not
for (var i=0; i<len; i++) {
var code = str.charCodeAt(i);
if (code>=97 && code<=122 && special) {
str = str.substr(0, i) + String.fromCharCode(code-32) + str.substr(i+1);
special = false;
}
else if (re.test(str[i])) {
special = true;
}
}
return str;
}
And finally, the template:
<script id="catagorie_list" type="x-tmpl-mustache">
<ul>{{#rows}}<li>{{capitalize_name}}</li>{{/rows}}</ul>
</script>

Categories

Resources