Javascript push into array without reference - javascript

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/>");
});
});

Related

How to get name and values from a javascript object into a new list?

I have this JavaScript object which is a collection of multiple lists(I believe). I need to create a select dropdown with the name being the name of the list, and a number of boxes with background color as per that name. Like this:
I am able to parse that object to get all the names of the colors, but I can't find a way to parse the names and the list of values it holds. This is how I tried :
var
YlGn3 = ['#f7fcb9', '#addd8e', '#31a354'],
YlGn4 = ['#ffffcc', '#c2e699', '#78c679', '#238443'],
YlGn5 = ['#ffffcc', '#c2e699', '#78c679', '#31a354', '#006837'];
var brewer = Object.freeze({
YlGn3: YlGn3,
YlGn4: YlGn4
});
var office = Object.freeze({
YlGn5: YlGn5
});
var colorschemes = {
brewer: brewer,
office: office
};
var scheme_list = [];
for (i in colorschemes){
for(j in colorschemes[i]){
console.log(j);
scheme_list.push(j);
}
}
I was thinking of creating a new object and append every color, along with the list of colors, so I can parse it again to create an option element with it. But, I am not able to figure out the best way to do that. Is this the correct approach ?
You use Object.values along with forEach multiple times.
Object.values(colorschemes).forEach(obj=>Object.entries(obj).forEach(([name,colors])=>{
const arr = [];
colors.forEach(color=>arr.push(color));
scheme_list.push([name, arr]);
}));
var
YlGn3 = ['#f7fcb9', '#addd8e', '#31a354'],
YlGn4 = ['#ffffcc', '#c2e699', '#78c679', '#238443'],
YlGn5 = ['#ffffcc', '#c2e699', '#78c679', '#31a354', '#006837'];
var brewer = Object.freeze({
YlGn3: YlGn3,
YlGn4: YlGn4
});
var office = Object.freeze({
YlGn5: YlGn5
});
var colorschemes = {
brewer: brewer,
office: office
};
var scheme_list = [];
Object.values(colorschemes).forEach(obj=>Object.entries(obj).forEach(([name,colors])=>{
const arr = [];
colors.forEach(color=>arr.push(color));
scheme_list.push([name, arr]);
}));
console.log(scheme_list);

how to get dynamically created object inserted into another object

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.

How to setup arrays in my case

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

how to create, assign and access new values to object?

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", ...), ... ]) );

creating list of objects in Javascript

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.

Categories

Resources