creating list of objects in Javascript - 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.

Related

How do i save multiple objects into an array

I have this object after click the save button.
{description: "ghhg", dateSelected: "2020-02-27", startDate: "2020-02-27", company_id: "2", hr_id:
72, …}
But whenever i click on save, it gives me a new object instead of storing it in array.
The question is how can i store each object inside an array to get
[
{description: "ghhg", dateSelected: "2020-02-27", startDate: "2020-02-27", company_id: "1" …},
{description: "grrrhhg", dateSelected: "2020-03-27", startDate: "2020-03-27", company_id: "2" …},
{description: "ghrtrhg", dateSelected: "2020-04-27", startDate: "2020-04-27", company_id: "2",  …},
.
.
.
]
This is my code
saveHolidays(hols : []){
this.holidays.hr_id = this.hrID.id;
this.getHolidayDate = this.holidays.dateSelected.split(" to ");
this.holidays.startDate = this.getHolidayDate[0];
this.holidays.endDate = this.getHolidayDate[1];
this.getHols = this.holidaysData;
this.holiday_date = [];
this.holidaysArray = [];
var tempHolidays = [];
this.getHols.forEach((element,key) => {
if(element.startDate){
this.holiday_date.push({startDate : element.startDate, endDate : element.endDate, company_id :
element.company_id})
}
});
var getElement = [];
let getStartDate = this.holiday_date.map(element => {
getElement.push(element.startDate, element.company_id);
return getElement;
});
for(var i = 0; i < getStartDate.length; i++){
var isStartDatePresent = getStartDate[i].includes(this.holidays.startDate);
var isCompanyIdPresent = getStartDate[i].includes(+this.holidays.company_id);
}
if(isStartDatePresent == true && isCompanyIdPresent == true ){
this.snotifyService.error('Holiday Already Exist');
}else{
hols = this.holidays;
for(var i = 0; i < hols.length; i++){
this.holidaysArray.push(hols[i]);
}
return this.holidaysArray
}
}
I'm a bit rusty, but if I remember correctly, JS arrays don't have fixed widths, so you might be able to push each saved holiday to an externally instantiated array or return one and set the desired external array to it.
You are reinitializing your array every time you click on save button by writing this.holidaysArray.
Removing it might solve your problem.
Set this.holidaysArray to an array ONLY IF it not already an Array.
/* REPLACE */
this.holidaysArray = []
/* WITH */
if (!Array.isArray(this.holidaysArray)) {
this.holidaysArray = []
}
Also, I highly recommend using a test-framework like Jest to test your code.
Good Luck...

JS converting an array to a json linked list?

I am new to JS and the concepts of organising data elude me a little, trying to take data from a specific array format (as this is what I have to work with) and output it into another specific JSON format.
This is to pass data to the D3 sankey module
https://github.com/d3/d3-plugins/blob/master/sankey/sankey.js
I can't figure out is how to add the index of the node into the links, rather than the name.
Really I am just totally lost with it!
I made a fiddle here:
https://jsfiddle.net/adamdavi3s/kw3jtzx4/
Below is an example of the data and the output required
var data= [
{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output= {
"nodes":[
{"name":"Agricultural 'waste'"},
{"name":"Bio-conversion"},
{"name":"Electricity grid"},
{"name":"Losses"},
{"name":"Liquid"}
],
"links":[
{"source":0,"target":1,"value":124.729},
{"source":1,"target":2,"value":0.597},
{"source":1,"target":3,"value":26.862},
{"source":1,"target":4,"value":280.322},
{"source":3,"target":4,"value":280.322}
]
};
Here is my code from the fiddle thusfar
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source};
var found = jQuery.inArray(node, sourceArray);
if (found < 0) {
// Element was not found, add it.
sourceArray.push(node);
}
}
console.log(sourceArray);
In javascript:
[ ] annotations are used to describe an Array, like:
var names=["John","Lisa"]
{ } Its are used to describe an Object
var person = {"name" : "John", "age" : 23}
You can use them inside one another
var people=[{"name" : "John", "age" : 23},{"name" : "Lisa", "age" : 44}]
Try this:
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var sourceArray=[];
var linkArray=[];
for (var i=0; i <data.length; i++ ) {
var node= {"name":data[i].source,};
var link= {
"source":i,
"target":data[i].target,
"value":data[i].value,
};
var found = jQuery.inArray(node, sourceArray);
if (found >= 0) {
// Element was found, remove it.
sourceArray.splice(found, 1);
linkArray.splice(found, 1);
} else {
// Element was not found, add it.
sourceArray.push(node);
linkArray.push(link);
}
}
finalArray={"nodes": sourceArray,"links": linkArray}
console.log(finalArray);
https://jsfiddle.net/9x4rdyy7/
Array.reduce() is perfect for this use case ;)
Take a look.
var data=[{"source":"Agricultural 'waste'","target":"Bio-conversion","value":"124.2729"},
{"source":"Bio-conversion","target":"Electricity grid","value":"0.597"},
{"source":"Bio-conversion","target":"Losses","value":"26.862"},
{"source":"Bio-conversion","target":"Liquid","value":"280.322"},
{"source":"Losses","target":"Liquid","value":"280.322"}
];
var output = data.reduce(function(result, item){
for(key in search = ['source','target']) {
var value = item[search[key]];
if(! result.index.hasOwnProperty(value)){
result.index[value] = Object.keys(result.index).length;
result.nodes.push({name: value});
}
}
result.links.push({
source: result.index[item.source],
target: result.index[item.target],
value: Number(item.value)
});
return result;
}, {nodes: [], links: [], index: {}});
delete output.index;
console.log(output);

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

How to build this json?

[{"username" : "11"},
{"password" : "test"},
{"detailorder" : [
{"id" : "1",
"qty" : "5"},
{"id" : "2",
"qty" : "10"}
]}
]
How di I create above json in javascript? I have very low understanding in json. I reffered to How do i build JSON dynamically in javascript?. I need to add data dinamically especially for detailorder. But I' stuck from beginning.
I wrote
var datajson = [];
And i dont know how to what to write next. Sorry for my bad english. Thanks
Create the array, assign it to a variable and stringify it.
Here is how:
var arr = [
{ username:'11' },
{ password:'test' },
{ detilpesanan: [
{ id:'1',jumlah:'5' },
{ id:'2',jumlah:'10' }
]}
];
var json = JSON.stringify(arr);
do you mean like:
var datajson = [
{ "username" : 11 },
{"password" : "test"},
{"orderdetail" :
{
"id": 1,
"qty": 25
},
{
"id": 2,
"qty": 10
}
}
];
Added:
var datajson = {};
datajson.username = 11;
datajson.password = "test";
datajson.detilpesanan = [];
datajson.detilpesanan.push({});
datajson.detilpesanan.unshift({});
datajson.detilpesanan[0]["id"] = 1;
datajson.detilpesanan[0]["jumlah"] = 5;
datajson.detilpesanan[1]["id"] = 2;
datajson.detilpesanan[1]["jumlah"] = 10;
console.log( datajson );
I'd like to suggest something to make it easier. First, you will need to use jquery, or any other javascript library that provides json parsing and endcoding. Then create that structure as a standard object on javascript. Use jquery ( or whatever javascript library you chose ), to encode it into a JSON string for you.
I have been using JSON format for years now, but I can barely recall the need to write it down myself. Maybe there were instances, but I think I did not use it for the actual implementation.
You can also go to json.org, and download parsers and encoders available.
I hope that helped.
You can see: http://www.json.org/js.html
JSON (Javascrtip Serialization Object) is a serialization object type, so you cant create objects and then serialize this object, like this:
function createPerson()
{
var persons = new Array();
for(i=0; i<3; i++)
{
var details = new Array();
for(k = 0; k<2;k++)
{
var det = new persondetail(k,k*2);
details.push(det);
}
var p = new person('user'+i,'pdw'+i,details);
persons.push(p);
}
//-- serialize object, see console output
console.log(JSON.stringify(persons));
}
function person(user, pwd,det)
{
this.username = user;
this.password = pwd;
this.detilpesanan = det;
}
function persondetail(id, jumlah)
{
this.id = id;
this.jumlah = jumlah;
}

Categories

Resources