How to update argument's value of list in JavaScript - javascript

I have a list with three empty objects like:
TimePickerList =[{},{},{}];
For example, I want to add 1 and 2 to the first argument of this list like this:
TimePickerList[0].push("1") // I know it's wrong and I can't use push like this.
TimePickerList[0].push("2")
And i want to get this:
TimePickerList =[{"1","2"},{},{}];
Is there any way to do this? I mean, can I update an argument's value?

Not really. I think you looking for an array with arrays.
const t = [[],[]];
t[0].push(1);
t[0].push(2)
console.log(t)

You can update values stored in arrays like such:
TimePickerList = [{}, {}, {}];
TimePickerList[0].a = 1;
console.log(TimePickerList)
// [{ a: 1 }, {}, {}]
The reason it wasn't working for you is because you were trying to push a value to an object. If you want to push values then push to an array, therefore using square brackets [] instead of curly braces {}.

Related

Push values to array but as object? JS

I need to push to array of object no array. Check my code..I don;t know where is my problem here
this.trainingPlan?.trainingTemplateExercises.push(this.singleTrainingInfo.trainingExercises.map(obj => {
return obj
}))
in this situation i push array of object. I need to push only object.
Like now i push [{obj...} , {obj2...}]
i need to push only {obj...} , {obj2...}
I need to push only object here..
This is now array like a
[ 0: [ obj1 , obj2]]
Your map here doesn't really do anything. It's just returning the same array you're mapping in the first place. Just concat the two arrays.
this.trainingPlan?.trainingTemplateExercises = this.trainingPlan?.trainingTemplateExercises.concat(this.singleTrainingInfo.trainingExercises)

AngularJS - Get object index in custom filter

I have made a custom filter in controller but can't get index or size of iterated json. Calling program.length gets me undefined. Any ideas?
$scope.filterFn = function(program){
if(case){
return true;
}
console.log(program.length);//undefined
return false;
};
try to use this code to get object length.
Object.keys(program).length;
try : How to display length of filtered ng-repeat data, so you can access size by $scope.filtered.length like the example.
Are there any more filters before this? Coz previous filters decide input for next filter?
The length() method is only available on an array [].
In this case you are trying to get the size of a json object {}, please note this does not have a length. If you need to see how many items exist in this object, you can try to first convert all the keys into an array by using Object.keys(program) which will give you an array.
If program originally looked like this:
{
foo: 'some value',
bar: 'another value'
}
using Object.keys(program) will give you ['foo', 'bar'] On this array you can now call the length method, so that you have Object.keys(program).length, which in this case would give you 2.

How to use underscore .groupBy function to group an array of json objects based on multiple properties?

I have an array of json objects who results I want to groupBy() based on multiple properties i.e.,
I have:
[
{
prop1:val1,
prop2:val2,
prop3:val3,
prop4:val4
}
]
Now if I just wanted to group by prop1 I guess I could have done :
_.groupBy(givenArray, 'prop1');
Now what should I do if I have to group by prop1,prop2 and prop3, i.e., (prop1 && prop2 && prop3)
Please guide.
You can put that target values to an array, and then form them to string, or just transform them to string form and combine:
_.groupBy(givenArray, function(item) {
var keys = _.pick(item, 'prop1', 'prop2', 'prop3');
// If all are string or number,
// return keys.join('_#%#_'); // this prevent ['ab', 'a'] generate same key to ['a', 'ba'];
return JSON.stringify(keys);
});
JSON.stringify maybe one of the many ways to create a combined key, I'm not sure what your vals is (string, number or else), so I'll just use stringify here.
It really depends on what you want your final structure to be.
If you don't mind a non-flat object structure, you can do nested _.groupBy calls:
var result = _(givenArray) //begin chain
.groupBy('a')
.mapValues(function(groupedByA) {
return _(groupedByA) //begin chain
.groupBy('b')
.mapValues(function (groupedByAAndB) {
return _.groupBy(groupedByAAndB, 'c');
})
.value(); //end chain
})
.value(); //end chain
//Then you can do things like:
result[5][4][3]; //All items where a=5, b=4, and c=3.
Downside here is that there's an extra level of nesting for each property you group by, and result[5][4] will blow up if there aren't any results where a=5 for example. (Though you could use a library like koalaesce for that)
Alternatively, if you want a flat object structure, but don't mind it being a bit ungainly to access the items, then:
var result = _.groupBy(givenArray, function (item) {
return JSON.stringify(_.pick(item, 'a','b','c'));
});
//Much simpler above, but accessed like:
result[JSON.stringify({a: 5, b:4, c:3})]
Much simpler and scales better to grouping by more things... but awkward to work with, since the keys are full JSON strings; but then you also don't have the null issue that the first option has.
You can also, just use _.values or some equivalent to turn the flat object structure into a single array of arrays. Then there's obviously no "random" access to get all items with a given value of a,b, and c, but you can always loop over it.

Javascript Double indexing Associative "array" Object [duplicate]

I am looking for a solution to create a single multidimensional associate array in javascript.
What I have: I have a mysql database I am accessing with php and have an array containing all fields (key,value pairs) in a single record. Their are upwards of 30 fields in each record so I am looking for a dynamic solution.
In the html coding, there is a form that is used to update a specific record in the table. I am using a function call on each input to fill a javascript array by key and value. The keys are identical to the keys in the php array.
In the function I am doing a json_encode call on the php array to pull in the "old" data to make it accessible to javascript.
What works: I am able to create a dynamic javascript associate array from the new data coming from the input function calls. I have tested this out using an alert after each call to the function.
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
This works:
var changes={};
function change(key,value) {
changes[key[value]]=value;
for (key in changes) {
alert('key: '+key+'... value: '+changes[key]);
}
}
this is along the lines of what I am looking for:
var changes={};
function change(key,value) {
var oldInfo = eval(<? echo json_encode($oldInfo); ?>); //this from the php array
changes[key[newValue]]=value;
changes[key[oldValue]]=oldInfo[key];
for (key in changes) {
alert('key: '+key+'... value: '+changes[key[newValue]]);
}
}
Can someone point me in the right direction?
To clarify:
My php array $oldInfo holds the old information from the table, for example:
{fName=>"charles",lName=>"madison", etc.}
The javascript array hold new information:
{fName=>"Charlie",lName=>"Madison", etc.}
I would like a new multidimentional array (PHP) (or object in JavaScript) that would look something like this:
{fName=>{"charles","Charlie"}, lName=>{"madison","Madison"}, etc.}
lName and fName would be the key fields that are synonymous to both the PHP array and the JavaScript object.
It's really unclear what you want, but there are a couple of serious flaws with your logic:
var changes={}; ///this one way of declaring array in javascript
No, it isn't. That's an Object, which is very different from an array.
eval(<? echo json_encode($oldInfo); ?>);
You don't need eval here. The output of json_encode is JSON, which is a subset of JavaScript that can simply be executed.
changes[key[value]]=value;
This is totally wrong, and still a single-dimensional array. Assuming key is an array, all you're doing is inverting the keys/values into a new array. If key looks like this before...
'a' => 1
'b' => 2
'c' => 3
... then changes will look like this after:
1 => 'a'
2 => 'b'
3 => 'c'
For a multidimensional array, you need two keys. You'd write something like changes[key1][key2] = value.
Your variable naming is wrong. You should never see a line that reads like this: key[value]. That's backwards. The key goes between the [], the value goes on the other side of the =. It should read something like array[key] = value.
RE: Your clarification:
This doesn't work: {fName=>{"charles","Charlie"},...}. You're confusing arrays and objects; Arrays use square brackets and implicit numeric keys (["charles", "Charlie"] for example) while Objects can be treated like associative arrays with {key1: "value1", key2: "value2"} syntax.
You want an array, where each key is the name of a property and each value is an array containing the old and new values.
I think what you want is actually quite simple, assuming the "value" you're passing into the function is the new value.
var changes = {};
var oldInfo = <?= json_encode($oldInfo) ?>;
function change(key, value) {
changes[key] = [ oldInfo[key], value ]
}
This :
changes[key[newValue]]
Should be:
changes[key][newValue]
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
Use aliases for the numeric indices to do this:
var foo = ["Joe","Blow"];
var bar = ["joe","blow"];
var names = {};
foo.fname = foo[0];
bar.fname = bar[0];
foo.lname = foo[1];
bar.lname = bar[1];
names.fname = [foo.fname,bar.fname];
names.lname = [foo.lname,bar.lname];

Create new multidimensional Associative array from 2 arrays

I am looking for a solution to create a single multidimensional associate array in javascript.
What I have: I have a mysql database I am accessing with php and have an array containing all fields (key,value pairs) in a single record. Their are upwards of 30 fields in each record so I am looking for a dynamic solution.
In the html coding, there is a form that is used to update a specific record in the table. I am using a function call on each input to fill a javascript array by key and value. The keys are identical to the keys in the php array.
In the function I am doing a json_encode call on the php array to pull in the "old" data to make it accessible to javascript.
What works: I am able to create a dynamic javascript associate array from the new data coming from the input function calls. I have tested this out using an alert after each call to the function.
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
This works:
var changes={};
function change(key,value) {
changes[key[value]]=value;
for (key in changes) {
alert('key: '+key+'... value: '+changes[key]);
}
}
this is along the lines of what I am looking for:
var changes={};
function change(key,value) {
var oldInfo = eval(<? echo json_encode($oldInfo); ?>); //this from the php array
changes[key[newValue]]=value;
changes[key[oldValue]]=oldInfo[key];
for (key in changes) {
alert('key: '+key+'... value: '+changes[key[newValue]]);
}
}
Can someone point me in the right direction?
To clarify:
My php array $oldInfo holds the old information from the table, for example:
{fName=>"charles",lName=>"madison", etc.}
The javascript array hold new information:
{fName=>"Charlie",lName=>"Madison", etc.}
I would like a new multidimentional array (PHP) (or object in JavaScript) that would look something like this:
{fName=>{"charles","Charlie"}, lName=>{"madison","Madison"}, etc.}
lName and fName would be the key fields that are synonymous to both the PHP array and the JavaScript object.
It's really unclear what you want, but there are a couple of serious flaws with your logic:
var changes={}; ///this one way of declaring array in javascript
No, it isn't. That's an Object, which is very different from an array.
eval(<? echo json_encode($oldInfo); ?>);
You don't need eval here. The output of json_encode is JSON, which is a subset of JavaScript that can simply be executed.
changes[key[value]]=value;
This is totally wrong, and still a single-dimensional array. Assuming key is an array, all you're doing is inverting the keys/values into a new array. If key looks like this before...
'a' => 1
'b' => 2
'c' => 3
... then changes will look like this after:
1 => 'a'
2 => 'b'
3 => 'c'
For a multidimensional array, you need two keys. You'd write something like changes[key1][key2] = value.
Your variable naming is wrong. You should never see a line that reads like this: key[value]. That's backwards. The key goes between the [], the value goes on the other side of the =. It should read something like array[key] = value.
RE: Your clarification:
This doesn't work: {fName=>{"charles","Charlie"},...}. You're confusing arrays and objects; Arrays use square brackets and implicit numeric keys (["charles", "Charlie"] for example) while Objects can be treated like associative arrays with {key1: "value1", key2: "value2"} syntax.
You want an array, where each key is the name of a property and each value is an array containing the old and new values.
I think what you want is actually quite simple, assuming the "value" you're passing into the function is the new value.
var changes = {};
var oldInfo = <?= json_encode($oldInfo) ?>;
function change(key, value) {
changes[key] = [ oldInfo[key], value ]
}
This :
changes[key[newValue]]
Should be:
changes[key][newValue]
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
Use aliases for the numeric indices to do this:
var foo = ["Joe","Blow"];
var bar = ["joe","blow"];
var names = {};
foo.fname = foo[0];
bar.fname = bar[0];
foo.lname = foo[1];
bar.lname = bar[1];
names.fname = [foo.fname,bar.fname];
names.lname = [foo.lname,bar.lname];

Categories

Resources