I've created a jTemplate to display an array of "test" objects. The array is a regular indexed array. The template is very basic, just uses a {#foreach} to iterate through the items in the array and displays them in a small table. This template dos the job and I get the expected output.
// Setup the JTemplate.
$('#tests_div').setTemplate($('#tests_template').html());
try {
// Process the JTemplate to display all currently selected tests.
$('#tests_div').processTemplate(_selectedTests);
}
catch (e) {
alert('Error with processing template: ' + e.Description);
}
<script type="text/html" id="tests_template">
{#foreach $T as tests}
<table>
<tr>
<td>Index: {$T.tests.index}</td>
<td>Name: {$T.tests.firstname} {$T.tests.lastname}</td>
<td>Score: {$T.tests.score} </td>
</tr>
</table>
{#/for}
</script>
What I'd like to do is change my array to be an associative array and store my objects in it using the test's index. This makes it easier to work with when I need to do some manipulation of the tests later on.
var a = new Test;
a.index = 12345678;
_selectedTests[a.index] = a;
However, when I pass the array to the template, I get an error about the script is causing my browswer to run slow, asking if I would like to stop it. It seems like its in some kind of endless loop. I'm not sure the template is reading the array correctly. Can anyone tell me how I work with the associative array inside the jTemplates?
You issue is that your array thinks it is huge:
_selectedTests[12345678] = a; // creates an array of 12345678 elements!! length of 12345678
so you can do this:
_selectedTests[a.index.toString()] = a; // creates an associative array with one key "12345678", length of 1
Related
I cannot put strings from the associative array to another associative array. This is very weird phenomenon. This is the code and result
[Code]
p.phone_score_list.map(par => {
console.log(`par`, par);
console.log(typeof par.ipa);
phoneScoreList.push({
ipa: par.ipa,
// ipa: par.phone,
phone: par.phone,
pronuncedIpa: par.pronuncedIpa,
qualityScore: par.quality_score,
soundMostLike: par.sound_most_like,
});
});
console.log(`phoneScoreList`, phoneScoreList)
The result is below.
"ipa" and "pronuncedIpa" are "n" in the par parameter but after inputting the ipa into another associative array like the above code, it's gonna be undefined. Do you know the reason and how to handle it?
This is phone_score_list.
It's possible that you're assigning references to an object that has since been dropped from memory. I would try to create a new object like so
const newObject = { ...par };
phoneScoreList.push(newObject);
We have a nested dataLayer variable on our booking platform. Users can make one or multiple variables are we want to pull out a string containing each of the product types contained within the array. I am hitting a error when debugging this however.
The location of the variable I would like to collect is:
dataLayer.booking.products[i].travelType
try{
var productList = {};
for(i=0;i<dataLayer.booking.products.length;i++){
productList[dataLayer.booking.products[i].travelType];
}
return productList.join('|');
}
catch(err){}
I am naive with JS so I apologies for a basic question.
M
Your code shows that you're setting a new property of the object productList, but you're not defining a value, e.g. {foo: } instead of {foo: "bar"}. It looks like what you want is an array that you can add strings to. For example:
var productList = dataLayer.booking.products.map(function(product) {
return product.travelType;
});
return productList.join('|');
Note that this is using the Array's map method as opposed to your for loop. You could also define productList as an array in a previous line, and then use the forEach method on the products Array to loop through every item, but I think this is cleaner and still legible. You can reduce the code further with ES6 syntax, but for your question it's probably better to show code that is more clearly defined.
I'm working with a web framework and I'm using variables from Python into Javascript code.
I get next array in Python, which can contain more than one cell with dictionaries inside it:
[[{'lacp_use-same-system-mac': u'no'}, {'lacp_mode': u'passive'}, {'lacp_transmission-rate': u'slow'}, {'lacp_enable': u'no'}]]
I want to be able to access every cell array and, after that, get every keys from the dictionary inside this cell array. Up to now, I only have arrays or dictionaries, so for both cases I did next:
var X = JSON.parse(("{{X|decodeUnicodeObject|safe}}").replace(/L,/g, ",").replace(/L}/g, "}").replace(/'/g, "\""));
Where X is the Python variable. Unfortunately, this does not run with the array I wrote above.
How can I do that?
Thanks beforehand,
Regards.
I want to be able to access every cell array and, after that, get
every keys from the dictionary inside this cell array
If I understood correctly you want to get the keys of a nested array.
Note: your array isn't valid js.
const arrarr = [[{key1: 'val1'}, {key2: 'val2'}], [{key3: 'val3'}, {key4: 'val4'}]];
arrarr.forEach(arr => {
arr.forEach(e => {
Object.keys(e).forEach(k => console.log(k))
})
})
If the depth of nests is of arbitrary depth you can use recursion and check if the child is an array, if it is keep going, else get the keys.
I have a component that is subscribed to some data used to populate a table. This table uses *ngFor to loop over the array of data and output it to the page, typical stuff.
When I define my array like so importResults: ImportResults[];, my data appears to get stored as intended and I am left with an array of objects.
ngOnInit() {
// Subscribe to our subject that lets us know about the added employees
this._massEmpService.importedData.subscribe(obj => {
if (obj) {
obj.checked = false;
this.importResults = obj;
}
});
}
With this setup, I can use *ngFor without issues by simply doing:
<tbody>
<tr *ngFor="let i of importResults" >
<td>
<input type="checkbox"
id="checkbox_{{ i.QID }}"
[checked]="i.checked"
(click)="toggleSelectedEmployee(i)"
[(ngModel)]="i.checked" />
</td>
...
</tr>
</tbody>
However... when I initialize my array like so importResults: ImportResults[] = []; it alters my data structure.
This leaves me with an array of arrays of objects?
This causes me to have to do some weird nested looping on my table which doesn't seem right.
<tbody *ngFor="let res of importResults">
<tr *ngFor="let i of res" >
<td>
<input type="checkbox"
id="checkbox_{{ i.QID }}"
[checked]="i.checked"
(click)="toggleSelectedEmployee(i)"
[(ngModel)]="i.checked" />
</td>
...
</tr>
</tbody>
Is this expected behavior to need to nest stuff like this? The first way works fine for how I would expect to be able to loop but because its not initialized, I can't push new data to it which is why I had to go with the expected way of defining it Array[] = [];
Am I doing something wrong here?
In your first instance, you declare the variable, but don't initialize it, then when you subscribe to the data service you assign the resulting array of objects to the variable:
this.importResults = obj;
In your second case, you declare the variable and initialize it as an empty array:
importResults: ImportResults[] = [];
Then when you get your data back from the service you're doing this:
this.importResults.push(obj);.
This is taking the returned array of objects from the data service and pushing it into the array you've already created, so that's why it ends up being nested. In the first, you're making your variable equal to the array of objects you're getting back, and in the second you're pushing the array of objects into the existing array.
If you used the same assignment in the second case:
this.importResults = obj;
You wouldn't have this problem, whether you initialized the variable to an empty array when you declared it or not.
If what you're trying to do is fetch one or more objects from a service and add them to an existing array, which may already have one or more objects inside, then you want to return the objects via subscribe, and iterate over them, pushing each object in that returned array one at a time into the existing array.
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];