Associative Arrays - Javascript - javascript

I am trying to populate an associative array, in a dynamic way. I have been reading a lot of documents but unable to figure out the right way.
The outcome of the code will be
op{
'0': value1, value2
'128': value3, value4, value 6
'630': value7
}
This is what i have written and is not working
var arr = [];
for(var i = 1; i <=last ; i++){
var key = rec[i].op;
var op = {};
op[key] = rec[i].description;
arr.push(op);
}
The most recent record is overwriting the previous record.

I think you want something like:
var op = {};
for(var i = 0; i < last ; i++)
{
var key = rec[i].op;
if (op[key] == undefined)
{
op[key] = [];
}
op[key].push(rec[i].description);
}

Related

Dynamic Key Value Array with Multiple Values in Javascript

I have:
var data = [];
I want to dynamically create string array like this:
for(var i=0; i < files.length; i++){
data[i].part1 = "abc";
data[i].part2 = "def";
data[i].part3 = "ghi";
}
Is this possible? I tried it and it complained 'Cannot set property 'part1' of undefined'
Then I want to sort the data array by part1 values so:
data[0] = {3,a,b};
data[1] = {1,a,b};
data[2] = {5,a,b};
becomes:
data[0] = {1,a,b,c};
data[1] = {3,a,b,c};
data[2] = {5,a,b,c};
The reason I want to do this is because after the sort is done, i need to change the
data[i].part2
to something else after sorting!
You could do this:
for (var i = 0; i < files.length; i++) {
data[i] = {};
data[i].part1 = "abc";
data[i].part2 = "def";
data[i].part3 = "ghi";
}
to set data[i] to an empty object, then fill it piece by piece. Or
for (var i = 0; i < files.length; i++) {
data[i] = {
part1: "abc",
part2: "def",
part3: "ghi"
};
}
to set data[i] to the complete object all at once.
I don't understand the data[0] = {3,a,b}; part, though: {3,a,b} is a syntax error and it doesn't resemble your other code (which doesn't mention 3 or a or b).
But you can easily sort an array of objects by a particular property:
data.sort(function (a, b) {
return (a.part1 > b.part1) - (a.part1 < b.part1);
});
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for details.

JavaScript for loop closure issue

I am adding all categories after ticking them to true if they exists in selected categories of result but it combines previous categories results with current one. I tried closure but it doesn't give me fresh object. Check out fiddle.
var allCatsResult = [{"id":1},{"id":2}, {"id":3}, ... ];
var catsArray = [1, 2] // Array of ids from allCatsResult
var result = [
{"id":1, selectedCategories:[{"id":1},{"id":2}]},
{"id":2, selectedCategories:[{"id":4},{"id":5}]},
...
];
for (var i = 0; i < results.length; i++) {
var tmp = allCatsResult; // tried to add function form here didn't work
for (var k = 0; k < results[i].selectedCategories.length; k++) {
var index = catsArray.indexOf(results[i].selectedCategories[k].category_id);
if(index !== -1) {
tmp[index].ticked = true;
}
}
results[i].categories = tmp;
}
Above code gives combined result for ticked = true for all categories in each result.
You need to copy/clone the array of objects, or you're manipulating the original. There are a few ways apparently. I chose the following:
var tmp = JSON.parse(JSON.stringify(allCatsResult));
This will create a new array of objects in tmp, and it will correctly only modify the clone.

javascript object reference by array

How can I refer to an object element dynamically during a loop by using an array, something like this:
var obj = {};
var lvl = ['x','y','z'];
var ol = [];
for (var l in lvl){
ol.push( lvl[l] )
obj[ol] = 'someval'
}
so where the reference may be obj[x][y][z] so each time the loop iterates, an additional key reference is appended, but I do not know how many levels there will be.
Not sure if I have explained that very well ?!
Based on how you answered my comment I believe this code will provide the nested object structure you are looking for.
var obj = {};
var lvl = ['x','y','z'];
var ol = {};
for (var i = 0; i < lvl.length; i++){
obj[i] = {};
ol = obj[key];
}
You mean you want someval to be the value of obj.x.y.z? You can always refer to the newly created levels using a variable:
var obj = {};
var levels = ['x','y','z'];
var pointer = obj;
for (var l=0; l<levels.length; l++) {
key = levels[l];
if (l < levels.length-1) { // if not last element
pointer[key] = {};
pointer = pointer[key];
}
else { // if last element
pointer[key] = 'someval';
}
}
console.log(obj); // should log {x:{y:{z:"someval"}}}

Copying array of objects into another array is it reference type in JQuery

I have a array of objects TransactionVModel.FiltersList[].
When I copy this array to another array fltrList[] and if I modify any of the object in array fltrList will it get reflect in Array TransactionVModel.FiltersList in JQuery ? For better clarity below is my example. As per me since it is a reference type it should update array TransactionVModel.FiltersList as well but in my scenario it is not happening, can I know why it is not happening ?
TransactionVModel.FiltersList is declared as ko.observableArray(); in my code.
function UpdateSelectedFilters(data) {
var fltrList = [];
fltrList = TransactionVModel.FiltersList();
for (var i = 0; i < data.length ; i++) {
var index = fltrList.indexOf(data[i]);
if (index != -1) {
var fltrObj = fltrList[index];
var fltrValArr = [];
fltrValArr = data.valueItems;
for (var j = 0; j < fltrValArr.length; j++) {
if (fltrValArr[j].IsSelected == true) {
if (fltrObj.indexOf(fltrValArr[j]) != -1) {
var selectedVal = fltrObj[fltrObj.indexOf(fltrValArr[j])];
selectedVal.IsSelected = true;
}
}
}
}
}
In my scenario I am updating selectedVal.IsSelected property but it is not reflecting the observableArray TransactionVModel.FiltersList.
You need to tell knockout that your array has changed with valueHasMutated:
function UpdateSelectedFilters(data) {
var fltrList = [];
fltrList = TransactionVModel.FiltersList();
//...
TransactionVModel.FiltersList.valueHasMutated();
}

Javascript arrays storing values

There might be a very simple solution my problem but just not being able to find one so please help me to get to my solution in the simplest way...
The issue here is that I have data being displayed in a tabular form. Each row has 5 columns and in one of the columns it shows multiple values and so that's why I need to refer to a value by something like this row[1]['value1'], row[1]['value2'] & then row[2]['value1'], row[2]['value2'].
I declare the array
var parray = [[],[]];
I want to store the values in a loop something like this
for(counter = 0; counter < 10; counter ++){
parray[counter]['id'] += 1;
parray[counter]['isavailable'] += 0;
}
Later I want to loop through this and get the results:
for (var idx = 0; idx < parray.length; idx++) {
var pt = {};
pt.id = parray[schctr][idx].id;
pt.isavailable = parray[schctr][idx].isavailable;
}
Obviously iit's not working because Counter is a numeric key and 'id' is a string key ..my question how do I achieve this ??
Thanks for all the answers in advance.
JS has no concept of "associative arrays". You have arrays and objects (map). Arrays are objects though, and you can put keys, but it's not advisable.
You can start off with a blank array
var parray = [];
And "push" objects into it
for(counter = 0; counter < 10; counter++){
parray.push({
id : 1,
isAvailable : 0
});
}
Then you can read from them
for (var idx = 0; idx < parray.length; idx++) {
// Store the current item in a variable
var pt = parray[idx];
console.log(pt);
// read just the id
console.log(parray[idx].id);
}
Like I did here
What you want inside your array is just a plain object:
// just a regular array
var parray = [];
for(var counter = 0; counter < 10; counter++){
// create an object to store the values
var obj = {};
obj.id = counter;
obj.isavailable = 0;
// add the object to the array
parray.push(obj);
}
later:
for (var idx = 0; idx < parray.length; idx++) {
var pt = parray[idx];
// do something with pt
}

Categories

Resources