Lets say I have the following in C
struct address{
char name;
int id;
char address;
};
struct address adrs[40]; //Create arbitrary array of the structure. 40 is example
adrs[0].name = 'a';
id[0] = 1;
...
What is the equivalent way of defining and creating array of a user defined structure.
Thanks
If you're going to have a predefined layout for an object, you'd probably want to use a contructor-style function.
function address() {
this.name = null;
this.id = null;
this.address = null;
}
arrays are not typed and you don't have to specify a length.
var adrs = [];
you can create a new instance of address like so
var item = new address(); // note the "new" keyword here
item.name = 'a';
item.id = 1;
// etc...
then you can push the new item onto the array.
adrs.push(item);
alernatively you can add a new item from the array and then access it by indexer.
// adrs has no items
adrs.push( new address() );
// adrs now has 1 item
adrs[0].name = 'a';
// you can also reference length to get to the last item
adrs[ adrs.length-1 ].id = '1';
Equivalent would be creating an array of associative arrays.
var arr = new Array();
arr[0] = { name: "name 1", id: 100, address: "addr 01" };
arr[1] = { name: "name 2", id: 101, address: "addr 02" };
//...
After this, you will be able to do:
arr[0].name = "new name 1";
Or access element:
if (arr[1].name == "name 2") { // will be true
}
Hope it helps.
Answer is veryyyy Simple.
const address = {
name: ""
id: 1,
address: ""
}
Or Dynamic
const address = (name, id, address) => {
// Here your checks if enters is correct
return {name, id, address}
}
If You Use TypeScript? It's so simple to.
interface address {
name: string;
id: number;
address: string;
}
const adress: adress = {
.....
}
<script type="text/javascript">
function address()
{
this.name="";
this.id=0;
this.address=""
}
var addresses = new Array(40);
addresses[0] = new address();
addresses[1] = new address();
.....
.....
addresses[0].name = 'a';
addresses[1].id = 5;
</script>
A common problem that is solved by structure is ranking system. An array that contains name and number of some users and then sorting users according to number. Here is javascript implementation of this problem.Object array is used here
<!DOCTYPE html>
<html>
<head>
<title>Structure</title>
</head>
<body>
<label>Enter Student Name 1:</label>
<input type="text" id='n0' name=""><br>
<label>Enter Student Mark 1:</label>
<input type="text" id='m0' name=""><br>
<label>Enter Student Name 2:</label>
<input type="text" id='n1' name=""><br>
<label>Enter Student Mark 2:</label>
<input type="text" id='m1' name=""><br>
<label>Enter Student Name 3:</label>
<input type="text" id='n2' name=""><br>
<label>Enter Student Mark 3:</label>
<input type="text" id='m2' name=""><br>
<input type="button" value="Ranking" onclick="result()">
<div id='id'></div>
<script type="text/javascript">
function result()
{
var b=new Array(100);
var n1=document.getElementById('n0').value;
var m1=document.getElementById('m0').value;
var n2=document.getElementById('n1').value;
var m2=document.getElementById('m1').value;
var n3=document.getElementById('n2').value;
var m3=document.getElementById('m2').value;
var a=new Array(100);
var b=new Array(100);
var n,m,j,i,temp,t,r="<br>Ranking<br><br>";
for(i=0;i<3;i++)
{
n=document.getElementById('n'+i).value;
m=document.getElementById('m'+i).value;
m=parseInt(m);
a[i]={name:n,mark:m};
}
for(i=0;i<3;i++)
{
for(j=i+1;j<3;j++)
{
if(a[j].mark>a[i].mark)
{
temp=a[i].mark;
t=a[i].name;
a[i].mark=a[j].mark;
a[i].name=a[j].name;
a[j].mark=temp;
a[j].name=t;
//console.log(a[i].name);
//console.log(a[i].mark);
}
}
}
for(i=0;i<3;i++)
{
r=r+a[i].name+" ";
r=r+a[i].mark+"<br>";
//console.log(a[i].name);
//console.log(a[i].mark);
}
document.getElementById('id').innerHTML=r;
}
</script>
</body>
</html>
Related
The primary objective of this application is to provide a search of a zipcode, followed by the display of the state associated with the zipcode once the zipcode has been located. How can I modify this code to reflect what it is that I am trying to acheive?
<input type="text" id="zipCode" placeholder="ZIP code" onKeyUp="validateZip()"/>
<div id="msg"></div>
function checkIfAvailable(zip)
{
let zones = [["90210","Beverly Hills"],
["90211","BH"]]
return( zones.indexOf(zip) >= 0 )
}
function validateZip()
{
let zip = document.getElementById("zipCode").value;
let msg =""
if(checkIfAvailable(zip)
{
msg="Our service is available in" + State
;
}
else
{
msg="Sorry our service is not available in this area";
}
document.getElementById("msg").innerHTML = msg;
}
if you can change the array to an object it would be as simple as:
let zones = {90210: "Beverly Hills", 90211:"BH"};
let msgElement = document.getElementById("msg")
function validateZip(userInput) {
if (userInput.value in zones) {
msgElement.innerHTML = "Our service is available in " + zones[userInput.value];
} else {
msgElement.innerHTML = "Sorry our service is not available in this area";
}
}
<input type="text" id="zipCode" placeholder="ZIP code" onKeyUp="validateZip(this)"/>
<div id="msg"></div>
checkIfAvailable can use find to return the inner array, if present:
function checkIfAvailable(zip) {
let zones = [...];
// Find an inner array where the first element [0]
// is the zip
return zones.find(item => item[0] === zip);
}
Then in validateZip:
const zone = checkIfAvailable(zip);
if (zone) {
// zone will be the matching inner array
// such as ["90210", "Beverly Hills"]
const State = zone[1];
msg = "Our service is available in " + State;
}
So, I am trying to POST form data to my API... and I wanted to add an array (multidimensional) to the post data, but i can't seem to figure it out.
Here's what i got so far:
let move_type = $("#move_type").text();
let loc_id = $("#loc_id").val()
// check a few vars first
let postvars;
postvars = $('#myForm input').serializeArray();
postvars.push({name: 'loc_id', value: loc_id}); //uncomment if you need to add vars in the postvars
postvars.push({name: 'move_type', value: move_type}); //uncomment if you need to add vars in the postvars
//loop through product ques
let prods_r = [];
$(".que_item").each(function(index){
let prod_id = $(this).find(".prod_id").text();
let title = $(this).find(".title").text();
let qty = $(this).find(".qty").val();
if(qty<1) {
showAlert("Please supply qty on all items in que. " + title);
return false;
}
prods_r[prod_id] = [];
prods_r[prod_id]["title"] = title;
prods_r[prod_id]["qty"] = qty;
})
postvars.push(prods_r);
When submitting this I get the variable for prods_r as "undefined" with no value.
I've also tried the following line to no avail
postvars.push({name: `prods_r`, value:prods_r });
I'm definitely missing something here ey?
You need to push all values to outer array else all values will get lost and it will return you empty array.
Demo Code :
$("form").on("submit", function(e) {
e.preventDefault()
let move_type = $("#move_type").text();
let loc_id = $("#loc_id").val()
let postvars;
postvars = $('#myForm input').serializeArray();
postvars.push({
name: 'loc_id',
value: loc_id
});
postvars.push({
name: 'move_type',
value: move_type
});
var dataa = new Array() //declare this
$(".que_item").each(function(index) {
let prod_id = $(this).find(".prod_id").text();
let title = $(this).find(".title").text();
let qty = $(this).find(".qty").val();
if (qty < 1) {
showAlert("Please supply qty on all items in que. " + title);
return false;
}
var prods_r = {}//create obj
//add value to it..
prods_r[prod_id] = {
"title": title,
"qty": qty
}
dataa.push(prods_r) //push in main array
})
postvars.push({
name: "prods_r",
value: dataa //passs it here
});
console.log(postvars)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="myForm">
<input tye="text" name="name" value="abc">
<input type="submit">
</form>
<div class="que_item">
<span class="prod_id">1</span>
<span class="title">Abcd</span>
<input tye="text" name="ded" class="qty" value="34">
</div>
<div class="que_item">
<span class="prod_id">2</span>
<span class="title">Abcd2</span>
<input tye="text" name="ded" class="qty" value="55">
</div>
HTML:
<html>
<body>
<input type = "text" name = "name" id = "name"> </input>
<button type = "submit" id = "submit">Find Student </button>
<script type = "text/javascript" src="ObjectTest.js"></script>
</body>
</html>
Javascript:
var Matt = {
GPA: 4.0,
Faculty: "Science",
Year: 1
};
I have an object that I've defined with some values.
What I am trying to do is to allow text to be entered into the textbox.
When the submit button is hit, a javascript function will be run that grabs the value in the textbox and if it equals the object value, then it will console.log the properties.
Here is my better attempt:
function findStudent(){
var student = document.getElementById('name').value;
return student;
}
console.log(student);
Hard to know exactly what you're trying to achieve or where your object is coming from but your object probably needs to look something like:
var student = {
name:'Matt',
gpa:4.0,
faculty:'Science',
year: 1
}
Try something like:
function checkName(){
var name = document.getElementById('name').val();
if(name === student.name){
console.log('same');
}
else{
console.log('different');
}
}
Called in your button, with something like:
<button onclick="checkName()">Check Student</button>
You have to think about the structure. There should be a lot of students. It's not practical to set multiple objects for each student:
var st1 = { ... }
var st2 = { ... }
Instead it's more practical to declare one object with all students. And put the values in an array:
var students = {
"Matt": ["4.0", "science", "1.0"],
"Laura": ["3.0", "comedy", "2.2"],
...
}
You can output the array as an info to the corresponding student:
function findStudent() {
var info = [];
var student = document.getElementById("name").value;
for (name in students) {
if (name === student) {
info = students[name];
}
}
alert(info);
}
JSFiddle
If you want to use a submit button, it should be in a form. This also makes dealing with inputs easier, even if you don't want to submit the form. I've modified the object so that it has a name property.
var Matt = {
name: 'Matt',
GPA: 4.0,
Faculty: "Science",
Year: 1
};
function checkValue(form) {
if (form.studentName.value == Matt.name) {
form.output.value = ('Match');
} else {
form.output.value = ('Not a match');
}
return false;
}
<form onsubmit="return checkValue(this);">
<label for="studentName">Name: <input name="studentName" id="studentName"></label>
<button>Check the name</button>
<br>
<label for="output">Output: <input name="output" id="output"></label>
</form>
The body of the checkValue function could be:
form.output.value = form.studentName.value == Matt.name? 'Match' : 'Not a match';
However the longer version is simpler to understand.
I need some help with figuring out how local storage and JSON works.
I have the following html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="Script.js"></script>
</head>
<body>
<form name="test" method="post" action="javascript:storage()">
<input name='surname' id="surname" value='surname'>
<input name='lastname' id="lastname" value='lastname'>
<input type="submit" value="test">
</form>
<div id="tabletest"></div>
</body>
</html>
the following javascript:
function storage(){
var surname = document.getElementById('surname').value;
var lastname = document.getElementById('lastname').value;
var person = {
"surname" : surname,
"lastname" : lastname,
"dateofbirth" : "01-01-1990"
};
person = JSON.stringify(person);
localStorage.setItem('person', person);
var person2 = localStorage.getItem('person');
var persons = JSON.parse(person);
var tabletest = document.getElementById('tabletest');
var person3 = JSON.parse(person2);
tabletest.innerHTML += JSON.stringify(person3);
}
My problems/troubles:
The output I get in tabletest is this:
{ "surname":"surname", "lastname":"lastname", "geboortedatum":"01-01-1990" }
How do I get only the surname and the lastname in the 'tabletest' div?
How do I add a new value with the inputs from the textfields when the submitbutton is clicked (because push doesn't work)?
To get lastname(or I should say any value inside JSON) use
tabletest.innerHTML +="Lastname:"+person3.lastname+" Sirname:"+person3.sirname;
And to add to the JSON use:
person.newName = newName
//or
person["newName"] = newName;
Localstorage works on key-value pairs. Since you are using the same key, 'person', you are simply overwriting previous value. You could use an array of persons which you store using 'person' key but you are responsible for parsing/stringifying the array each time.
var personsStore = [];
function storage() {
var s = localStorage.getItem("person");
if (s) {
personsStore = JSON.parse(s);
}
var person = {...} //after you get properties from dom input
personsStore.push(person);
var stringForm = JSON.stringify(personsStore");
localStorage.setItem("person", stringForm);
var tabletest = document.getElementById('tabletest');
tabletest.innerHtml += stringForm;
}
If you want particular attributes the easiest way to do that is to use a tool like underscore (underscore.org). Appending to 'tabletest' becomes
tabletest.innerHtml += JSON.stringify(_.map(personStore, fucntion(p) {
return _.pick(p, "firstname", ....);
});
Here is a fiddle
Right now, your logic shows you grabbing the value of first and last name, which is, currently: surname and lastname, respectively:
<input name='surname' id="surname" value='surname'>
<input name='lastname' id="lastname" value='lastname'>
You need to run this function on the button click event and get the value and simply use the storage setItem(key,value) function. Here is the documentation . You only need to stringify, then parse on the storage data. After that, it is an object that you can get the properties from.
person = JSON.stringify(person);
localStorage.setItem('person', person);
var person2 = localStorage.getItem('person');
var persons = JSON.parse(person2);
var tabletest = document.getElementById('tabletest');
tabletest.innerHTML += persons.surname + ' ' + persons.lastname;
You were very close on the logic, but you needed something like this:
document.getElementById('btnTest').onclick = storage;
I also modified the 'submit' button to a standard 'button' element so that the form doesn't post:
<button id='btnTest' value="test">Test</button>
You could then do Ajax. Otherwise, you would need to do a pre-submit function
I have a set of nesting json object like this:
var obj = {
name: "student",
contact: {
phone: "22222",
fax: "33333",
...
},
...
}
And I have these text fields:
<input type="text" name="name" />
<input type="text" name="contact_phone" />
<input type="text" name="contact_fax" />
...
Now I want to fill these fields with appropriate property from above object. My question is how can I access anonymous property from that object?
For example suppose I have this jquery code:
$("#formID").find("input").each(function(index) {
fieldName = $(this).attr("name");
var namePart = fieldName.split("_");
//I want something like this: console.log(obj.namePart[0].namePart[1])
});
Use obj["propertyName"]
obj[namePart[0]][namePart[1]]
$('#formID').find("input").each(function(index) {
fieldName = $(this).attr("name");
var namePart;
if(fieldName.indexOf('_') > -1){
namePart = fieldName.split("_");
console.log(obj[namePart[0]][namePart[1]])
}
else{
namePart = fieldName;
console.log(obj[namePart])
}
});
*Note: The property is not anonymous. If your run obj["propertyName"] on an object with no such property it will return undefined.
<form ID="formID">
<input type="text" name="name" />
<input type="text" name="contact_phone" />
<input type="text" name="contact_fax" />
</form>
$("#formID").find("input").each(function() {
fieldName = $(this).attr("name");
namePart = fieldName.split("_");
if(namePart.length ==1 && namePart[0]=="name"){
$(this).val(obj.name);
}
else if(namePart.length>1){
$(this).val(obj[namePart[0]][namePart[1]]);
}
//I want something like this: console.log(obj.namePart[0].namePart[1])
});
http://jsfiddle.net/57vL6b0w/
Edit: Sorry about that I misunderstood the question. What you are looking for is something like this.
var obj = {
name: "student",
contact: {
phone: "22222",
fax: "33333"
}
};
$('#formID').("input").each(function(index) {
fieldName = $(this).attr("name");
var namePart = fieldName.split("_");
var arbitraryVal = obj;
for (var part in namePart) {
if (arbitraryVal.hasOwnProperty(namePart[part])) {
arbitraryVal = arbitraryVal[namePart[part]];
continue;
}
arbitraryVal = null;
break;
}
if (typeof $(this).val(arbitraryVal) !== 'undefined') {
$(this).val(arbitraryVal);
}
});
recusivly searches an object for each name part. If the name part is
contact_phone It will look for obj.contact.phone if it is something_else_with_lots_of_underscores it will look for obj.something.else.with.lots.of.underscores
JS FIDDLE