How to create, assign and access new values to object ?
Declaring new objects and adding new values to is is problem for me.
can any one help me?
var Countries = [
{
name : 'USA',
states : [
{
name : 'NH',
cities : [
{
name : 'Concord',
population : 12345
},
{
name : "Foo",
population : 456
}
/* etc .. */
]
}
]
},
{
name : 'UK',
states : [ /* etc... */ ]
}
]
Tried like this:
Countries = new Array();
Countries[0] = new Country("USA");
Countries[0].states[0] = new State("NH");
Countries[0].states[0].cities[0] = new city("Concord",12345);
Countries[0].states[0].cities[1] = new city("Foo", 456);
...
Countries[3].states[6].cities[35] = new city("blah", 345);
You're trying to create new objects over and over with things like new Country and new State but you don't have those defined as functions. Something much more simple should work:
Countries[0].states[0].name = "Not New Hampshire";
console.log(Countries[0].states[0].name);
[Edit] : I also highly agree with upsidedown. Please check a tutorial on working with data structures (arrays and objects) in JavaScript.
As #uʍop-ǝpısdn commented, you'll find lots of tutorials.
One of the common pattern for creating "newable" objects in JavaScript goes like this:
var Country = function(name, states){
this.name = name;
this.states = states || [];
}
var State = function(name, cities){
this.name = name;
this.cities = cities || [];
}
var Countries = [];
Countries.push( new Country("USA", [ new State("NH", ...), ... ]) );
Related
This is super frustrating to me so I hope someone can help. The below is a small example to illustrate my problem.
var group = {
names: []
}
var groupList = {
group: [],
activity:[]
}
$(document).ready(function(){
$("#play").click(function(){
var soccer = group;
var person = "Jack";
soccer.names.push(person);
var person = "Amber";
soccer.names.push(person)
groupList.group.push(soccer); //group[0]
// how do I make a constructor for a new group?
var soccer1 = group;
var person = "Jill";
soccer1.names.push(person)
groupList.group.push(soccer1); //group[1]
// expect group 0 to be [Jack,Amber] (but pushing Jill on group1 updates group0)
$("#beta").append("Soccer Group: "+groupList.group[0].names +"<br/>");
// expect group 1 to be either [Jack,Amber,Jill] or [Jill]
$("#beta").append("Soccer Group: "+groupList.group[1].names +"<br/>");
});
});
I need to create a new instance of group without changing the original group.
https://jsbin.com/hetenol/edit?html,js,output
EDIT: The following will only work if you plan to fill the arrays Game.player and Game.score with primitives.
You could clone the arrays like this:
AllGames.games.push({
player: [...Game.player],
score: [...Game.score]
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
Solution to the question:
var soccer1 = jQuery.extend(true,{}, group);
You can use a function called "group" as a constructor.
function group() {
this.names = [];
}
var groupList = {
group: [],
activity:[]
}
$(document).ready(function(){
$("#play").click(function(){
var soccer, soccer1, person;
soccer = new group();
person = "Jack";
soccer.names.push(person);
person = "Amber";
soccer.names.push(person)
groupList.group.push(soccer); //group[0]
soccer1 = new group();
person = "Jill";
soccer1.names.push(person)
groupList.group.push(soccer1); //group[1]
// expect group 0 to be [Jack,Amber]
$("#beta").append("Soccer Group: "+groupList.group[0].names +"<br/>");
// expect group 1 to be [Jill]
$("#beta").append("Soccer 1 Group: "+groupList.group[1].names +"<br/>");
});
});
Good morning!
i have two dynamically created objects using form fields values. They are object literals which look like this:
var courses = {};
course['name'] = $('#course').val();
var students = {};
students['first'] = $('#first_name').val();
students['last'] = $('#last_name').val();
students['age'] = $('age').val();
I would like to insert them in a single object literal var person= {}
i need the two objects into one because I need to stringify it and send via ajax to my process page. Could you please help me?
You can populate an object as you are creating it:
var persons = {
courses: {
name: $('#course').val(),
},
students: {
name: $('#first_name').val(),
last: $('#last_name').val(),
age: $('#age').val(),
},
};
If you want to use the objects that you already have then you can do so:
var persons = {
courses: courses,
students: students,
};
You can create a object with the 2 objects like:
var data = {courses:courses,students:students};
or you can append one to the other
students['courses'] = courses;
And what's the problem?
Just place these objects into your object and then you can serialize it e.g. to JSON and send via ajax:
var person = {}
person.course = {};
person.student = {};
person.course['name'] = "Course 1";
person.student['first'] = "Vasya";
person.student['last'] = "Pupkin";
person.student['age'] = "26";
If you want multiple students, you should use arrays. Here we create an array with 3 objects, each represents a student:
var person = {}
person.course = {};
person.students = [{},{},{}];
person.course['name'] = "Course 1";
person.students[0]['first'] = "Vasya";
person.students[0]['last'] = "Pupkin";
person.students[0]['age'] = "26";
person.students[1]['first'] = "Petya";
person.students[1]['last'] = "Vasechkin";
person.students[1]['age'] = "30";
person.students[2]['first'] = "Vasiliy";
person.students[2]['last'] = "Alibabaevich";
person.students[2]['age'] = "40";
You can do the same thing with courses.
But in this case the name person for the object that contains all this data a bit confusing, because it contains multiple students. You should give meaningful names for your variables.
I need to create a array like the following
var new = 'New';
var old = 'Old';
var posterArray = [new, old];
//I want to push posterType and posterYear into new and old array
var posterType = [{'id':123, 'name':'test'}, {'id':456, 'name':'test'}];
var posterYear = [{'year':12345, 'status':'old'}, {'year': 3456, 'name':'old'}];
Is there anyway I can push posterType and posterYear into new and old variable inside the posterArray? For example, posterArray[0].push(postertype). Basically I need mullti-dimentional array and I am not sure how to accomplish here. Thanks for the help!
Seems like this would suffice your needs:
var posterArray = {
new: null,
old: null
};
Then later on:
posterArray.new = [{'id':123, 'name':'test'}, {'id':456, 'name':'test'}];
posterArray.old = [{'year':12345, 'status':'old'}, {'year': 3456, 'name':'old'}];
And you can even do:
var newObj = {
id: 234,
name: 'newtest'
};
posterArray.new.push(newObj);
EDIT Also heed ryanyuyu's warning: new is a reserved keyword in javascript
I am working on YUI DataTables, to populate the data table i want to send the columns and their values dynamically from outside, for that i have written the following code:
<html>
<script src="http://yui.yahooapis.com/3.17.2/build/yui/yui-min.js"></script>
<div class="example yui3-skin-sam" id="simple"> <!-- You need this skin class -->
</div>
<script>
var cols = ["id", "name", "price"];
var obj = {
id: "",
name: "",
price: ""
};
var data2 = new Array();
obj.id = "ga";
obj.name = "gadget";
obj.price = "$6.99";
data2.push(obj);
obj.id = "ga2";
obj.name = "gadget2";
obj.price = "$7.99";
data2.push(obj);
obj.id = "ga3";
obj.name = "gadget3";
obj.price = "$8.99";
data2.push(obj);
YUI().use("datatable", function (Y) {
// A table from data with keys that work fine as column names
var simple = new Y.DataTable({
columns: cols,
data : data2,
summary: "Price sheet for inventory parts",
caption: "Example table with simple columns"
});
simple.render("#simple");
});
</script>
</html>
now the problem is that, it shows only the last obj pushed in data2.. kindly tell me why its not displaying all three objs. the resulting table from this code is
id name price
ga3 gadget3 $8.99
Not sure if this is relevant anymore but if people still come here looking for an easy solution...
Just stringify the object and JSON.parse it again to copy it instead of referencing the object like so;
data2.push(JSON.parse(JSON.stringify(obj)));
it will give all array values
function obj(id, name, price) {
this.id = id;
this.name = name;
this.price = price;
}
var array = new Array();
var point = new obj("ga", "gadget", "$6.99");
array.push(point);
var point = new obj("ga2", "gadget2", "$7.9");
array.push(point);
Both answers above (2480125, 2480125) will work, but they require that you manually input the new object's properties for every new object added to the array.
You can avoid that inflexibility with a for..in loop (docs):
var newObj = function(object) {
var newObject = {};
for (var key in object) {
if (object.hasOwnProperty(key)) {
newObject[key] = object[key];
}
}
return newObject;
};
var obj = {
id: 'foo',
name: 'gadget',
price: '$6.99'
};
data2 = [];
data2.push( newObj(obj) );
obj.id = 'bar';
obj.name = 'baz';
obj.price = '$4.44';
data2.push( newObj(obj) );
console.log(data2);
data2.forEach(function(item){
console.log("%s, %s, %s", item.id, item.name, item.price);
});
// data2 now contains two distinct objects, rather than one object reference added to the array twice.
JSFiddle for above code
Objects are reference objects.
obj.id = "ga";
obj.name = "gadget";
obj.price = "$6.99";
data2.push(obj);
obj.id = "ga2";
obj.name = "gadget2";
obj.price = "$7.99";
data2.push(obj);
This means that when you update the obj the second time, you're actually updating all references to that object.
If you examine your data2 array you'll see that it has 3 elements and that all elements are the same.
try updating your code to something like this
data2.push({
id : "ga",
name : "gadget",
price : "$6.99"
});
data2.push{(
id : "ga2",
name : "gadget2",
price : "$7.99"
)};
data2.push({
id : "ga3",
name : "gadget3",
price : "$8.99"
});
None of these answers worked for me, and I can't explain why it worked, but adding a character value to the element I was pushing inline was the only way I could get it to work properly. I tried the suggestions of creating new objects or even just creating new variables and pushing either the new object or new variables but to no avail, it just kept rewriting each element of the array whenever it would push a new element such that the entire array would be the final value of the loop each time. So in the end this is what I had to do to get it to work:
var returnArray = [];
while(...){
returnArray.push('' + obj.value);
}
Is it possible to do create a list of your own objects in Javascript? This is the type of data I want to store :
Date : 12/1/2011 Reading : 3 ID : 20055
Date : 13/1/2011 Reading : 5 ID : 20053
Date : 14/1/2011 Reading : 6 ID : 45652
var list = [
{ date: '12/1/2011', reading: 3, id: 20055 },
{ date: '13/1/2011', reading: 5, id: 20053 },
{ date: '14/1/2011', reading: 6, id: 45652 }
];
and then access it:
alert(list[1].date);
dynamically build list of objects
var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
listOfObjects.push(singleObj);
});
here's a working example http://jsfiddle.net/b9f6Q/2/
see console for output
Maybe you can create an array like this:
var myList = new Array();
myList.push('Hello');
myList.push('bye');
for (var i = 0; i < myList .length; i ++ ){
window.console.log(myList[i]);
}
Going off of tbradley22's answer, but using .map instead:
var a = ["car", "bike", "scooter"];
a.map(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
return singleObj;
});
Instantiate the array
list = new Array()
push non-undefined value to the list
var text = list.forEach(function(currentValue, currentIndex, listObj) {
if(currentValue.text !== undefined)
{list.push(currentValue.text)}
});
So, I'm used to using
var nameOfList = new List("objectName", "objectName", "objectName")
This is how it works for me but might be different for you, I recommend to watch some Unity Tutorials on the Scripting API.