How do i save multiple objects into an array - javascript

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...

Related

How do I get items from localStorage?

In my app I've got 2 functions to work with localStorage.
When I add the first and second items, it works properly, but when it is the third item, it gives an error.
Here are the functions:
w.getLocalStorage = function() {
var c = localStorage.getItem('cities');
var arr = [];
arr.push(c);
return c ? arr : [];
}
w.setLocalStorage = function(data, googleData, cities, name) {
if (data) {
city.name = data.name;
city.coord.lat = data.coord.lat;
city.coord.lon = data.coord.lon;
cities.push(JSON.stringify(city));
// console.log(city);
localStorage.setItem("cities", cities);
} else if (googleData) {
city.name = name;
city.coord.lat = googleData.results[0].geometry.location.lat;
city.coord.lon = googleData.results[0].geometry.location.lng;
console.log('cities', cities);
cities.push(JSON.stringify(city));
// console.log(cities, city);
localStorage.setItem("cities", cities);
}
}
Here is what it returns for the first 2 items:
Array[1]
0 : "{"name":"Pushcha-Voditsa","coord":{"lat":50.45,"lon":30.5}}"
1 : "{"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
Here is what when the third items is added:
Array[1]
0 : "{"name":"Pushcha-Voditsa","coord":{"lat":50.45,"lon":30.5}}, {"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
1 : "{"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
How can I fix this?
As you can only store string in localStorage, to persist object convert them in stringified format using JSON.stringify() method and on retrieval use JSON.parse() to parses the JSON string to construct the JavaScript value or object.
Here are the code snippet, which require attention. You should persist stringified cities data
cities.push(city);
localStorage.setItem("cities", JSON.stringify(cities));
While retrieval, parse it JavaScript object
var cities = localStorage.getItem('cities');
var c = cities ? JSON.parse(cities) || [];

Can't iterate into javascript array of objects

I come to you because i have some issues using javascript arrays.
I'm trying to iterates through a javascript array filled with some objects.
I have totally 4 objects.
this is my code :
// sort trainings_tab descending order
trainings_tab = trainings_tab.sort(function(a, b) {
if (a.date_from < b.date_from)
return 1;
else if(a.date_from > b.date_from)
return -1;
return 0;
});
console.log(trainings_tab);
for(var h = 0; h < trainings_tab.length; h++) {
// var training = new_array[h];
console.log(trainings_tab[h]);
}
and what i've got from console.log(trainings_tab); =>
[] (i have a little blue i here that say : object value at left was snapshotted when logged value below was evaluated just now)
0: Object
_geoloc: Object
_highlightResult: Object
_rankingInfo: Object
address: "Hospital da plastica, Rio de Janeiro, Brazil"
address_id: 16623
date_from: "1479769200"
date_to: "1480028400"
device: "USD"
doctor_full_name: "John Doe"
doctor_id: "85"
doctor_image: "/images/avatar_85.jpg"
doctor_url: "/profile/85"
guest: "2"
labo_id: "8So7KJPmv4qyL2uHD"
langues: "English"
objectID: "689"
objectives: Array[2]
price: "1000"
procedures: Array[1]
products: Array[1]
seat_left: "2"
seat_taken: 0
speciality: "PLASTIC SURGERY, BODY CONTOURING"
training_full: ""
training_name: "Lipofacillomaxial"
url: "/training/detail/689"
__proto__: Object
1: Object
2: Object
3: Object
length: 4
__proto__: Array[0]
Each objects looks like the first one, with other datas ofc.
But the problem is that my for loop doesn't iterate other the array and i can't see the console.log(trainings_tab[h]);
Someone has an idea and can help me plz ? Thanks.
EDIT : HOW DO I POPULATE MY TAB ?
i assign a var at empty tab :
var trainings_tab = [];
I use ALGOLIA (https://www.algolia.com/) to search into an index called 'training' and that get all my records. When the search is done i have a callback and i'm doing this :
function searchDone(err, content) {
if (err) {
console.error(err);
return;
}
//console.log(content.hits);
for(var i = 0; i < content.hits.length; i++) {
var training = content.hits[i];
// check that's a training
if (training && training.date_from != null) {
// calculate seats taken
var seats_taken = training.guest - training.seat_left;
var training_full = '';
// training is full ?
if (training.seat_left == 0) training_full = 'training-full';
training.seat_taken = seats_taken;
training.training_full = training_full;
if (training.hidden == false || training.hidden == null)
Session.set("countTrainings", Session.get("countTrainings")+1);
trainings_tab.push(training);
}
}
}
It seems that my problem is when i populate the trainings_tab, because if i console.log before the sort, i have the same display than quoted before...

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

Issue Pushing values in to objects Javascript

Have some issue with push the values in to the javascript array object. Please any one give me the perfect solution
Class code :
var myfuns = ( function(undefined) {
var myarr ={};
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
}
}
function _getList() {
return $.extend(true, {}, myarr);
}
return {
add : _add,
getList : _getList
}
}());
Here am calling and manage the values and keys
function setmydetails(){
var my_param = {
current_info : {
pg : '#tset',
no : 12,
name : "john",
row : 0,
},
userprofile : [],
class : [],
marks : [],
games : []
};
myfuns.add(my_param);
}
Now i got the array
myfuns.getList() // GOT proper array what i passed in my_param
Question : How to modify the existing values from any one of the Inner array from the myarr Obj
Ex: Once First array created later have to modify some from "myarr.current" = > Change current_info.row to 2222
Similar i have to add some array in to " myarr.class " etc
I would like to say try this one not tested
function _add(arrayparam){
if (myarr.current == undefined) {
myarr.current = [];
myarr.current.push(options.current_info);
}else{
$.extend( myarr.current, arrayparam);
}
}
proper source : https://api.jquery.com/jquery.extend/

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