how to get dynamically created object inserted into another object - javascript

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.

Related

Create a Listed (Nested) Element in a Javascript object

My question comes from this answer to a similar question. The comment below the answer sums up my question
how would the code look like if you would like to give depth to the tree? Like for name i would like to give name.firstname and name.lastname. Would I need to define name as var?
This is my current code
var jsonOutput = new Object();;
jsonOutput.workflowID=1234;
jsonOutput.author="jonny"
I want to create a javascript object that looks like the below. I am stuck with creating the list of Tools. How would I do this?
{
"workflowID": "1234",
"author": "jonny",
"tools": [
{
"toolid": "543",
"type": "input",
},
{
"toolid": "3423",
"type": "input",
},
{
"toolid": "1234",
"type": "merge",
"on": "Channel Name"
}
]
}
Create a data object
Populate the inner hierarchy with values
Add a tools array to data
Create tool object and populate
Push tool to the tools array
Repeat
var data = {};
data.workflowID = 1234;
data.author = "jonny";
data.tools = [];
let tool = {};
tool.toolid = 543;
tool.type = "input";
data.tools.push(tool);
tool = {};
tool.toolid = 3423;
tool.type = "input";
data.tools.push(tool);
tool = {};
tool.toolid = "1234";
tool.type = "merge";
tool.on = "Channel Name";
data.tools.push(tool);
console.log(data);
Technically, to create a more complex object, you can just do something like:
tool543 = new Object();
tool543.toolid = "543";
tool543.type = "input";
jsonOutput.tools = []; // Now .tools is an empty array
jsonOutput.tools.push(tool543); // And now you're appending to it.

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 do I programmatically build an object from my form data that includes arrays

I need to display some values on a jsp page, grab input from user and send it back to a controller that is using Jackson to bind it to my backing data object. Several rows that I display on the screen are backed by an array and are created with <c:forEach> and I'm generating a path like "blobs[0].id" and "blobs[0].text". When I try to put them into the json object to be sent back to the controller by an ajax call, they aren't being added to the object properly. The property name ends up having "[0]" in the name instead of representing the object at that array index.
<script>
var formData = {};
formData.blobs = [];
formData.blobs[0] = {};
formData.blobs[0].id = "English";
formData.blobs[0].text = "Hello";
formData["blobs[1].id"] = "German";
formData["blobs[1].text"] = "Guten Tag";
console.log(formData);
</script>
ends up looking like {blobs: [0 : {id: "English", text: "Hello"}], blobs[1].id: "German", blobs[1].text: "Guten Tag"} instead of
{blobs: [0 : {id: "English", text: "Hello"}, 1 : {id: "German", text: "Guten Tag"}]}
I am trying to assemble the model thusly:
<script>
function createModel() {
var form = $("#theForm");
var formData = {};
$.each(form, function(i, v){
var input = $(v);
if (input.attr("name")) {
formData[input.attr("name")] = input.val();
}
});
}
</script>
Accessing obj["attr"] is an option to access an object's attribute, so obj["attr[1][22]"] will access an attribute called "attr[1][22]", while accessing obj["attr"][1][22] will access the second element of obj.attr, and the second element's 22th element as well..
The solution will be to access formData["blobs"][0].id or even formData["blobs"][0]["id"]
you can format the string to your needs
$('#yourform').serializeArray() returns an array:
[
{"name":"foo","value":"1"},
{"name":"bar","value":"xxx"},
{"name":"this","value":"hi"}
]
$('#yourform').serialize() returns a string:
"foo=1&bar=xxx&this=hi"
so, in your case
var formData = {};
formData.blobs = [];
$('#yourform').serializeArray().forEach(function(blob){
formData.blobs.push({
id: blob.name,
text: blob.value
});
})

Pushing objects in an array only returns last object pushed

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

how to use array to store list of contacts

I am learning angular.js. I am trying to create an app with gmail chat box like implementation. So as a first step I created an implementation where you can create groups and add members from the available contacts array.
First I will show all group available if you click on add group I will show you list of contacts from where you can click on the particular contact I will take the index and add it to new array and then push it into a my contact array.
Here is part of my code
app.factory('contactfactory', function (){
var factory = {};
factory.contacts = [
{email:"vicky-1"},
{email:"vicky2"},
{email:"vicky3"},
{email:"vicky4"},
{email:"vicky5"},
{email:"vicky6"},
{email:"vicky7"},
{email:"vicky8"},
{email:"vicky9"},
{email:"vicky10"},
{email:"vicky11"},
{email:"vicky12"},
{email:"vicky13"},
{email:"vicky14"},
{email:"vicky15"},
{email:"vicky16"},
{email:"vicky17"},
{email:"vicky18"}
];
factory.myGroups = [{
groupName: "Avangers",
members: ["vicky-1","vicky2","vicky3"]
}];
factory.getGroups = function (){
return factory.myGroups;
};
factory.getContacts = function (){
return factory.contacts;
};
factory.newcontact = [];
factory.newGroup = {};
factory.createMember = function (index) {
console.log(factory.contacts[index].email);
factory.newcontact.push(factory.contacts[index].email);
console.log("inside createmem()" + factory.newcontact);
};
factory.createGroup = function (groupName) {
factory.newGroup.groupName = groupName;
factory.newGroup.members = factory.newcontact;
factory.myGroups.push(factory.newGroup);
console.log(factory.newGroup);
factory.newcontact = [];
};
return factory;
});
the error i get is
Duplicates in a repeater are not allowed. Use 'track by' expression to
specify unique keys. Repeater: group in groups, Duplicate key:
object:019
this my code in jsfiddle
http://jsfiddle.net/vickyvignesh/E6NzM/

Categories

Resources