Update object key value - javascript

Been trying to figure this out for the past hour, but can't seem to get it. I am trying to make an array with the dates of the last X days. Here is an example:
var dates = [];
var curr = new Date();
var first = curr.getDate();
dates.push(new Date(curr.getTime()).toISOString().split('T')[0]);
for(var i = 1; i < 6; i++){
var previous = new Date(curr.getTime());
previous.setDate(first - i);
dates.push(previous.toISOString().split('T')[0]);
}
console.log(dates);
The result gives me:
["2014-03-18", "2014-03-17", "2014-03-16", "2014-03-15", "2014-03-14", "2014-03-13"]
How would I put that in this format for my chart?
var chartData = [{day: '2014-03-18',clicks: 8,success: 4},
{day: '2014-03-17',clicks: 41,success: 3},
{day: '2014-03-16',clicks: 20,success: 1},
{day: '2014-03-15',clicks: 46,success: 3},
{day: '2014-03-14',clicks: 34,success: 2}];
I need to be able to add clicks and success as well, but since the varaible name is dynamic I am having a hard time. I tried bracket notations, along with dots and I can't get it to work.
Anyone know how I would achieve this?
Thank you in advance!

Fundamentally, to put an object in your array rather than a string, you create the object:
dates.push({
day: previous.toISOString().split('T')[0],
clicks: 0,
success: 0
});
Then later to update:
++dates[someIndex].success;
or
dates[someIndex].clicks = 27;
You said:
...but since the varaible name is dynamic I am having a hard time
...but didn't say what variable you were talking about. If you mean the name of the property, like click or success, that's okay, you can use bracketed notation and a string:
var obj = {day: previous.toISOString().split('T')[0]};
obj[variableWithNameForClicks] = 0;
obj[variableWithNameForSuccess] = 0;
dates.push(obj);
and
++dates[someIndex][variableWithNameForSuccess];
or
dates[someIndex][variableWithNameForClicks] = 27;
That works because in JavaScript, you can access object properties in two ways: Dotted notation with a literal property name (obj.foo), or bracketed notation with a string property name (obj["foo"]). In the bracketed notation, the string can be the result of any expression, including a variable lookup. So:
var obj = {clicks: 27};
var str = "clicks";
console.log(obj[str]); // 27

See the codepen here.
var dates = [];
var curr = new Date();
var first = curr.getDate();
// Using variable object property names
var dayVar = "day";
var clicksVar = "clicks";
var successVar = "success";
// Increment from 0 instead of 1 so you don't have to repeat yourself
for ( var i = 0; i < 6; i++ ){
var dateObj = {};
var previous = new Date(curr.getTime());
previous.setDate(first - i);
dateObj[dayVar] = previous.toISOString().split('T')[0];
dateObj[clicksVar] = 0;
dateObj[successVar] = 0;
dates.push(dateObj);
}
// Increment clicks
dates[0][clicksVar] += 1;
// Increment success
dates[0][successVar] += 1;
console.log(dates);
If you want to go back and find the object for a certain date, you might use a js library like underscore, or you could do something like this:
// Today's date
var searchDate = new Date(curr.getTime()).toISOString().split('T')[0];
// Search through the array for the matching object
for (var i = 0; i < searchDate.length; i++) {
var obj = dates[i];
if ( obj.day === searchDate ) {
console.log(obj);
break;
}
}

Related

Javascript replace .something with a var

I want to replace "Sensor1" with a variable, since I want to change what this command does inside a for loop (the number of sensor):
for(var i=1; i < len; i ++){
let timestamps = [];
let values = [];
var d = cdata[i];
ts_measures.forEach(ts_measure => {
//console.log(ts_measure.val().timestamp, ts_measure.val().value);
timestamps.push(ts_measure.val().time);
values.push(ts_measure.val().Sensor1);
});
I have already tried this option, but it doesnt seems to work:
for(var i=1; i < len; i ++){
let timestamps = [];
let values = [];
var d = cdata[i];
ts_measures.forEach(ts_measure => {
//console.log(ts_measure.val().timestamp, ts_measure.val().value);
timestamps.push(ts_measure.val().time);
values.push(ts_measure.val().d);
});
I am triying to replace "Sensor1" in the first fragment of code, with d (a variable) as you can see in the second fragment.
cdata[0] = "Sensor1";
cdata[1] = "Sensor2";
I would really aprecciate any help.
You can access a property of an object with its name as a string using myObject["myPropertyName"] syntax.
So in your case, considering cdata[0] = "Sensor1"; cdata[1] = "Sensor2"; and that you retrieve the string value with your d variable... just use ts_measure.val()[d] to access property value.
for(var i=1; i < len; i ++){
let timestamps = [];
let values = [];
var d = cdata[i]; // retrieve "Sensor1" (and following "SensorX" string)
ts_measures.forEach(ts_measure => {
//console.log(ts_measure.val().timestamp, ts_measure.val().value);
timestamps.push(ts_measure.val().time);
values.push(ts_measure.val()[d]); // using `[d]` to retrieve property value
});
In JavaScript, you can access a value of an object either by this method:
const obj = {a: 1, b:2};
console.log(obj.a);
or by this other one:
console.log(obj['a']);
So you can try using bracket notation with string or variable inside

Javascript add object to an oustide array in a loop

I'm trying to add dynamically created Javascript object to an array. I could traverse the DOM & creating the objects. But when displaying the final array of Objects, the count is correct but all objects are of same value ie, final index value. How to get rid of this problem?
PS: DOM traversal & other functionalities work well & only problem with creating the final array of objects with correct values.
Javascript Code.
var match = {};
var matches = [];
$('.SIsort').each(function (i, v) {
console.log("type.."+typeof matches);
var date = $(this).find('td:eq(0)').find('meta')[0].content;
var team1 = $(this).find('td:eq(1)').find('div:eq(1)').text();
var team2 = $(this).find('td:eq(1)').find('div:eq(3)').text();
var loc = $(this).find('td:eq(2)').find('div:eq(0)').text();
match.date = date;
match.team1 = team1;
match.team2 = team2;
match.venue = loc;
console.log(match); // It displays Correctly
(matches = window.matches || []).push({});
matches = (window.matches || []).push(match);
// console.log(matches[i])
});
console.log(matches); // All object values belong only to final index
You're repeatedly pushing the same object into the array.
Move your
var match = {};
...line into the loop so that you create a new object each time.
Also, I'm not sure what you're trying to achieve with this:
(matches = window.matches || []).push({});
matches = (window.matches || []).push(match);
But you just want:
matches.push(match);
Here's a minimal example of what you're doing:
var match = {};
var i;
for (i = 0; i < 5; ++i) {
match.i = i; // Overwrites the previous `i` value on subsequent loops
matches.push(match); // Pushes the *same object* onto the array
}
console.log(matches); // Shows the same object, all with `i = 4`
Instead, create a new object each time:
var i;
for (i = 0; i < 5; ++i) {
var match = {}; // Creates a new object
match.i = i;
matches.push(match);
}
console.log(matches);
Applying that to your code:
var matches = [];
$('.SIsort').each(function (i, v) {
console.log("type.."+typeof matches);
var date = $(this).find('td:eq(0)').find('meta')[0].content;
var team1 = $(this).find('td:eq(1)').find('div:eq(1)').text();
var team2 = $(this).find('td:eq(1)').find('div:eq(3)').text();
var loc = $(this).find('td:eq(2)').find('div:eq(0)').text();
var match = {};
match.date = date;
match.team1 = team1;
match.team2 = team2;
match.venue = loc;
console.log(match); // It displays Correctly
matches.push(match);
});
console.log(matches);
Side note: These lines:
var match = {};
match.date = date;
match.team1 = team1;
match.team2 = team2;
match.venue = loc;
console.log(match); // It displays Correctly
matches.push(match);
can be combined into:
var match = {
date: date,
team1: team1,
team2: team2,
venue: loc
};
console.log(match); // It displays Correctly
matches.push(match);
The problem with your code is that you're creating only ONE instance of match outside of your loop and updating the same object in each iteration before adding it to your Array. Actually you're supposed to create a NEW object, every time you want to add an entry to your loop, so create a new object at the starting of the loop like below.
var matches = [];
$('.SIsort').each(function (i, v) {
var match = {};
// update match object and add to array
matches.push(match);
}
That should do it :)

js Array undefined after json declaration

I m new a web developer and i face up the following problem:
"Cannot read property 'length' of undefined"
my code:
var data=();
for(var i;i<parseInt(window.localStorage["numOfInserts"]);i++){
data["category_name"]=localStorage.getItem(("category_name_"+i).toString());
data["category_id"]=localStorage.getItem(("category_id_"+i).toString());
data["provider_name"]=localStorage.getItem(("provider_name_"+i).toString());
data["provider_id"]=localStorage.getItem(("provider_id_"+i).toString());
data["appointment_date"]=localStorage.getItem(("appointment_date_"+i).toString());
data["appointment_time"]=localStorage.getItem(("appointment_time_"+i).toString());
}
$scope.allAppointments=dataArray;
for(var i=0;i<dataArray.length;i++){
$scope.showme[i]=false;
}
After some research I understand that the problem caused to the fact that data is an array but I try to turn it to json, but
var data ={};
gives me the same error as before.
Please Help me
I think this is what you're looking for, see code comments:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array, using the information
// from local storage. Note that you don't need toString() here.
// Once we've created the object (the {...} bit), we push it onto
// the array
data.push({
category_name: localStorage.getItem("category_name_"+i),
category_id: localStorage.getItem("category_id_"+i),
provider_name: localStorage.getItem("provider_name_"+i),
provider_id: localStorage.getItem("provider_id_"+i),
appointment_date: localStorage.getItem("appointment_date_"+i),
appointment_time: localStorage.getItem("appointment_time_"+i)
});
}
This does the same thing, it's just more verbose and so could help you understand more clearly what's going on:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array
var obj = {};
// Fill it in from local storage. Note that you don't need toString() here.
obj.category_name = localStorage.getItem("category_name_"+i);
obj.category_id = localStorage.getItem("category_id_"+i);
obj.provider_name = localStorage.getItem("provider_name_"+i);
obj.provider_id = localStorage.getItem("provider_id_"+i);
obj.appointment_date = localStorage.getItem("appointment_date_"+i);
obj.appointment_time = localStorage.getItem("appointment_time_"+i);
// Push the object onto the array
data.push(obj);
}
You need to create an array(dataArray before the loop), and create a new object in each iteration and set the property values for that object then add the object to the array like below
var dataArray = [],
data, numOfInserts = parseInt(window.localStorage["numOfInserts"]);
for (var i = 0; i < numOfInserts; i++) {
data = {};
data["category_name"] = localStorage.getItem(("category_name_" + i).toString());
data["category_id"] = localStorage.getItem(("category_id_" + i).toString());
data["provider_name"] = localStorage.getItem(("provider_name_" + i).toString());
data["provider_id"] = localStorage.getItem(("provider_id_" + i).toString());
data["appointment_date"] = localStorage.getItem(("appointment_date_" + i).toString());
data["appointment_time"] = localStorage.getItem(("appointment_time_" + i).toString());
dataArray.push(data)
}
$scope.allAppointments = dataArray;
for (var i = 0; i < dataArray.length; i++) {
$scope.showme[i] = false;
}
It looks like you're trying to create an associative array, so the first line should indeed be
var data = {};
The next part is fine, but then it looks like you want to enumerate the keys
for(var i=0;i<Object.keys(data).length;i++){
$scope.showme[i]=false;
}

Can't pass arrays in multidimensional array to other function using setInterval

I have a multidimensional array named "thisIsMyContainerArray" that holds content of two other arrays. What I'm trying to do is check each item in the "thisIsMyContainerArray" array and log each item (in this case, two other arrays) from that array separately in the console, and do so every 5 seconds. So far I have the following code:
var thisIsMyContainerArray = new Array();
var thisIsMyArray1 = new Array('val1', 'val2', 'val3', 'val4');
var thisIsMyArray2 = new Array('valA', 'valB', 'valC', 'valD');
thisIsMyContainerArray.push(thisIsMyArray1, thisIsMyArray2);
for (var i = 0; i < thisIsMyContainerArray.length; i++) {
var t1 = setInterval(tester,5000);
function tester() {
console.log(thisIsMyContainerArray[i]);
}
}
And I always get the following output in my console, every 5 seconds:
["val1", "val2", "val3", "val4"]
["val1", "val2", "val3", "val4"]
This is my desired result, I need to see this in the console instead of the output I mentioned earlier:
["val1", "val2", "val3", "val4"]
["valA", "valB", "valC", "valD"]
Any help would be greatly appreciated since I've been stuck on this for a few hours now and I just can't figure it out. :( I tried passing it to the tester function but then it turns out as "undefined".
try this - you should be able to get this working if it is not at the moment..
var thisIsMyContainerArray = new Array();
var thisIsMyArray1 = new Array('val1', 'val2', 'val3', 'val4');
var thisIsMyArray2 = new Array('valA', 'valB', 'valC', 'valD');
thisIsMyContainerArray.push(thisIsMyArray1, thisIsMyArray2);
var t1 = setInterval(tester,5000);
function tester()
{
for (var i = 0; i < thisIsMyContainerArray.length; i++)
{
console.log(thisIsMyContainerArray[i]);
}
}
If I test this code in a clean environment, all it outputs is undefined, so its probably because the i variable isn't passed along, nor contained within a closure scope. Basically, there is an i variable somewhere in the global namespace set to 0, which is the one used.
Also, I'm not sure if you're doing more with the t1 variable, but its being reset at every loop, so you're going to get rogue intervals.
If the logging is all you're after, I'd do this:
var thisIsMyContainerArray = new Array();
var thisIsMyArray1 = new Array('val1', 'val2', 'val3', 'val4');
var thisIsMyArray2 = new Array('valA', 'valB', 'valC', 'valD');
thisIsMyContainerArray.push(thisIsMyArray1, thisIsMyArray2);
var t1 = setInterval(tester,5000);
function tester() {
for (var i = 0; i < thisIsMyContainerArray.length; i++) {
console.log(thisIsMyContainerArray[i]);
}
}
If this is just a simplified example and you need the original structure with a loop and setting multiple intervals for each array, try this:
var thisIsMyContainerArray = new Array();
var thisIsMyArray1 = new Array('val1', 'val2', 'val3', 'val4');
var thisIsMyArray2 = new Array('valA', 'valB', 'valC', 'valD');
thisIsMyContainerArray.push(thisIsMyArray1, thisIsMyArray2);
function tester(index) {
console.log(thisIsMyContainerArray[index]);
setTimeout(function() {
tester(index);
}, 5000);
}
for (var i = 0; i < thisIsMyContainerArray.length; i++) {
tester(i);
}

Group array items based on variable javascript

I have an array that is created dynamic from an xml document looking something like this:
myArray[0] = [1,The Melting Pot,A]
myArray[1] = [5,Mama's MexicanKitchen,C]
myArray[2] = [6,Wingdome,D]
myArray[3] = [7,Piroshky Piroshky,D]
myArray[4] = [4,Crab Pot,F]
myArray[5] = [2,Ipanema Grill,G]
myArray[6] = [0,Pan Africa Market,Z]
This array is created within a for loop and could contain whatever based on the xml document
What I need to accomplish is grouping the items from this array based on the letters so that all array objects that have the letter A in them get stored in another array as this
other['A'] = ['item 1', 'item 2', 'item 3'];
other['B'] = ['item 4', 'item 5'];
other['C'] = ['item 6'];
To clarify I need to sort out items based on variables from within the array, in this case the letters so that all array objects containing the letter A goes under the new array by letter
Thanks for any help!
You shouldn't use arrays with non-integer indexes. Your other variable should be a plain object rather than an array. (It does work with arrays, but it's not the best option.)
// assume myArray is already declared and populated as per the question
var other = {},
letter,
i;
for (i=0; i < myArray.length; i++) {
letter = myArray[i][2];
// if other doesn't already have a property for the current letter
// create it and assign it to a new empty array
if (!(letter in other))
other[letter] = [];
other[letter].push(myArray[i]);
}
Given an item in myArray [1,"The Melting Pot","A"], your example doesn't make it clear whether you want to store that whole thing in other or just the string field in the second array position - your example output only has strings but they don't match your strings in myArray. My code originally stored just the string part by saying other[letter].push(myArray[i][1]);, but some anonymous person has edited my post to change it to other[letter].push(myArray[i]); which stores all of [1,"The Melting Pot","A"]. Up to you to figure out what you want to do there, I've given you the basic code you need.
Try groupBy function offered by http://underscorejs.org/#groupBy
_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
Result => {1: [1.3], 2: [2.1, 2.4]}
You have to create an empty JavaScript object and assign an array to it for each letter.
var object = {};
for ( var x = 0; x < myArray.length; x++ )
{
var letter = myArray[x][2];
// create array for this letter if it doesn't exist
if ( ! object[letter] )
{
object[letter] = [];
}
object[ myArray[x][2] ].push[ myArray[x] ];
}
Demo fiddle here.
This code will work for your example.
var other = Object.create(null), // you can safely use in opeator.
letter,
item,
max,
i;
for (i = 0, max = myArray.length; i < max; i += 1) {
item = myArray[i];
letter = myArray[2];
// If the letter does not exist in the other dict,
// create its items list
other[letter] = other[letter] || [];
other.push(item);
}
Good ol' ES5 Array Extras are great.
var other = {};
myArray.forEach(function(n, i, ary){
other[n[2]] = n.slice(0,2);
});
Try -
var myArray = new Array();
myArray[0] = [1,"The Melting Pot,A,3,Sake House","B"];
myArray[1] = [5,"Mama's MexicanKitchen","C"];
myArray[2] = [6,"Wingdome","D"];
myArray[3] = [7,"Piroshky Piroshky","D"];
myArray[4] = [4,"Crab Pot","F"];
myArray[5] = [2,"Ipanema Grill","G"];
myArray[6] = [0,"Pan Africa Market","Z"];
var map = new Object();
for(i =0 ; i < myArray.length; i++){
var key = myArray[i][2];
if(!map[key]){
var array = new Array();
map[key] = array;
}
map[key].push(myArray[i]);
}

Categories

Resources