Make use of a global array - javascript

I want to use the values that I get from a request, but the response object is a local variable (an array). Therefore I create this global array:
<script type="text/javascript">
var response = [];
as you see, right under the script opening tag, so it is global. Then in the function where I have the response I added this:
jsonResponse.forEach(function(element){
response[element.size] = element.id;
});
And then added this, with the purpose to make use of the values that I've got in my global var from the response object:
getIdOfProductBySize: function() {
var selectedIndex = document.getElementById('dropdown_options').value;
for (var key in response) {
if (key != selectedIndex) {
continue;
} else {
return response[key];
}
}
}
Doesn't work, so I started going step by step (of the order I add the new things) and I noticed that the script breaks after the 2nd thing that I add (where the forEach is).
Maybe I am not declaring the global variable correctly, or maybe I cannot access it this way, or maybe I don't assign the values to it in the correct way, I don't know, so I am asking if someone can give me a hint how to make use of all this working together?

Try this:
var response = {key1: value1};
var i = 2;
jsonResponse.forEach(function(entry) {
console.log(entry);
response["key"+i] = entry.id;
i++;
});
var index;
for (index = 0; index < response.length; ++index)
{
console.log(response[index]);
if(response["key"+index] !== selectedIndex)
continue;
else
return response["key"+index];
}

Looks like you're going to need a two dimensional array.
Looks to me like your "key" value is undefined.
before:
for (var key in response) {
try:
var k=response.whatever;
If that makes sense?

response[element.id] = element.size;
Try this one, i believe element.size returns the actual size of an element and is not what you want to use as index in an array.

Related

Add values from one array to object with specified key & index

Im using the following code,
jQuery.each(aDataSel, function(index, oData) {
oPushedObject = {};
aSelectedDataSet.push(fnCreateEnt(aProp, oData, oPushedObject));
});
This is aSelectedDataSet values
and this is the values of OData
What I need is that before I do the push is to fill the listTypeGroup & listTypeGroupDescription (with the red arrow ) with values that Are inside the oData -> ListTypeGroupAssigment -> result (listTypeGroup & listTypeGroupDescription) , The index is relevant since I want to add just the value of the index in each iteration (since this code is called inside outer loop and the index determine the current step of the loop) ,How it can be done nicely?
The result contain 100 entries (always) and the a selected data will have 100 entries at the end...
Update :)
Just to be clear In the pic I show the values which is hardcoded for this run but the values can be any values, we just need to find the match between the both objects values...
I mean to find a match between to_ListTypeGroupAssigment in both object (which in this case exist ) and if in oData there is result bigger then one entry start with the matching ...
UPDATE2 - when I try Dave code the following happen for each entry,
This happen in the Jquery.extend line...any idea how to overcome this?
The following hard-coded of Dave:-) work perfect but I need generic code which doesnt refer to specific field name
jQuery.each(aDataSet, function(index, oData) {
oPushedObject = {};
fnCreatePushedEntry(aProperties, oData, oPushedObject);
var result = oData.to_ListTypeGroupAssignment.results[index];
oPushedObject.to_ListTypeGroupAssignment = {
ListTypeGroup: result.ListTypeGroup,
ListTypeGroupDescription: result.ListTypeGroupDescription
};
aSelectedDataSet.push(oPushedObject);
});
Im stuck :(any idea how to proceed here ?what can be wrong with the extend ?
should I use something else ? Im new to jQuery...:)
I think that this happen(in Dave answer) because the oData[key] is contain the results and not the specified key (the keyValue = to_ListTypeGroupAssignment ) which is correct but we need the value inside the object result per index...
var needValuesForMatch = {
ListTypeGroup: 'undefined',
ListTypeGroupDescription: 'undefined',
}
//Just to show that oPushedObject can contain additional values just for simulation
var temp = {
test: 1
};
//------------------This object to_ListTypeGroupAssigment should be filled (in generic way :) ------
var oPushedObject = {
temp: temp,
to_ListTypeGroupAssignment: needValuesForMatch
};
oPushedObject is one instance in aSelectedDataSet
and after the matching I need to do the follwing:
aSelectedDataSet.push(oPushedObject);
Is this what you're after:
OPTION ONE - DEEP CLONE FROM oData TO aSelectedDataSet
aSelectedDataSet.forEach(function(currentObject,index){
for (var childObject in currentObject) {
if (! currentObject.hasOwnProperty(childObject))
continue;
var objectToClone = oData[childObject]['results'][index];
if(objectToClone)
$.extend(true,currentObject[childObject],objectToClone);
}
});
Here is your data in a fiddle with the function applied: https://jsfiddle.net/hyz0s5fe/
OPTION TWO - DEEP CLONE FROM oData ONLY WHERE PROPERTY EXISTS IN aSelectedDataSet
aSelectedDataSet.forEach(function(currentObject,index){
for (var childObject in currentObject) {
if (! currentObject.hasOwnProperty(childObject))
continue;
if(typeof currentObject[childObject] !== 'object')
continue;
for(var grandChildObject in currentObject[childObject]) {
var objectToClone = oData[childObject]['results'][index][grandChildObject];
if(typeof objectToClone === 'object') {
$.extend(true,currentObject[childObject][grandChildObject],objectToClone);
} else {
currentObject[childObject][grandChildObject] = objectToClone;
}
}
}
Fiddle for option 2: https://jsfiddle.net/4rh6tt25/
If I am understanding you correctly this should just be a small change:
jQuery.each(aDataSel, function(index, oData) {
oPushedObject = {};
fnCreateEnt(aProp, oData, oPushObj);
//get all the properties of oData and clone into matching properties of oPushObj
Object.getOwnPropertyNames(oData).forEach(function(key) {
if (oPushObj.hasOwnProperty(key)) {
//oPushObj has a matching property, start creating destination object
oPushObj[key] = {};
var source = oData[key];
var destination = oPushObj[key];
//can safely assume we are copying an object. iterate through source properties
Object.getOwnPropertyNames(source).forEach(function(sourceKey) {
var sourceItem = source[sourceKey];
//handle property differently for arrays
if (Array.isArray(sourceItem)) {
//just copy the array item from the appropriate index
destination[sourceKey] = sourceItem.slice(index, index + 1);
} else {
//use jQuery to make a full clone of sourceItem
destination[sourceKey] = $.extend(true, {}, sourceItem);
}
});
}
});
aSelectedDataSet.push(oPushedObject);
});
It is unclear what exactly your fnCreateEnt() function returns though. I am assuming it is the populated oPushObj but it's not entirely clear from your question.

Get array from dynamic variable

I'm sure this is really simple, I just can't work out how to do it.
I want to dynamically make an array from one variable equal to another:
var pageID = document.getElementsByClassName('page_example')[0].id;
Let's say this returned an id of page_1
var page_1 = ['value1','value2','value3'];
var page_2 = ['value4','value5','value6'];
var page_3 = ['value7','value8','value9'];
var page_array = (then have the associated pageID's array here)
So in this example,
page_array would equal ['value1','value2','value3']
Instead of storing the array in separate variables, store them in an object with the ids as the key:
var pages = {
page_1: ['value1','value2','value3'],
page_2: ['value4','value5','value6'],
page_3: ['value7','value8','value9']
}
You can access the arrays as though the object was an assosiative array:
var pageID = "page_1";
var pageArray = pages[pageID];
Depending on what you would like to achieve, you can one of two or three methods.
What I consider the easiest method is an if/else statement:
if (condition) {
page_array = page_1.slice(0);
} else if (other condition) {
page_array = page_2.slice(0);
} else if...
Another method you can use, again depending on what your ultimate goal is, would be a for loop:
for (var i = 0; i < numOfDesiredLoops; i++) {
page_array = page_1.slice(0, i);
}
Or you could use a combination of both:
for (var i = 0; i < numOfDesiredLoops; i++) {
if (condition) {
page_array = page_1.slice(0);
} else if (other condition) {
page_array = page_2.slice(1);
} else if...
}
With more information on why you need this variable to change, I can give you a better answer.
edit: keep in mind the arguments of .slice() can be whatever you want.

Add to array only once - leaving unique items

I program a function that give me all values of some input checkboxes and include them into an array.
Function:
$('#area_tbl .checkbox').each(function(){
/*for(var i = 0; i < test.length; i++){
if(test[i].PLZ === $(this).find('.area-checkbox').val()){
alert('Gleich');
}else{
alert('nicht gleich');
}
}*/
test.push({PLZ:$(this).find('.area-checkbox').val()});
});
My array looks like this:
[Object { PLZ="42799"}]
That's fine!
Now I include automatically more checkboxes with more values. After that my function is refreshing and I include the 'new' values.
Now my problem is that my array looks like this:
[Object { PLZ="42799"}, Object { PLZ="42799"}, Object { PLZ="51399"}]
You can see PLZ='42799' is twice.
I want to find the duplicate values and delete them from my array. I try it with the if clause in my function. But nothing works for me.
Assuming that value of each checkbox is unique, you need to reset the test value before running this each iterator
test = [];
$('#area_tbl .checkbox').each(function(){
test.push({PLZ:$(this).find('.area-checkbox').val()});
});
You could use a memory
// The memory will be a simple list with the already added elements. Firstly empty
memory = []
// we loop over ther checboxes
$('#area_tbl .checkbox').each(function(){
// we store the value
var v = $(this).find('.area-checkbox').val();
// If memory doesn't content the value... (its position is -1)
if(memory.indexOf(v) == -1){
// we store the object and we update the memory
test.push({PLZ:v});
memory.push(v);
}
});
You could use a temporary object and look up with accessing the property:
var object= {};
$('#area_tbl .checkbox').each(function() {
var v = $(this).find('.area-checkbox').val();
if (!object[v]) {
test.push({PLZ: v});
object[v] = true;
}
});

how to parse json array

I'm trying to parse something like this
{
"popular result":[
{"term":"Summer","url":"http://summer.com"},
{"term":"Autumn","url":"http://autumn.com"},
{"term":"spring","url":"http://spring.com/"},
{"term":"winter","url":"http://winter.com/"}]
}
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i = 0; i < json.length; i++) {
$.each(myJson.i, function (key, value) {
alert(value.term);
});​
}
});
});
</script>
but nothing happened! Because is array in array! Please let me know how to do this
Arrays and objects are different things. You will want to investigate them tons more before things get really challenging.
Assuming json really does equal the object you provide (in JSON those show up as {}), then json['popular result'] (you could use a . if there wasn't a space) is the array (in JSON those show up at []) you want to traverse.
For some reason, this confusion got you looping over an object (not going to get you anywhere as length is rarely defined for it) and then (ignoring the typo on myJson), you started looping over something that didn't exist (which didn't crash b/c it never got there).
Cleaning it up...
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/Controls/GetPopularSearches', function (json) {
for (var i=0;i<json['popular result'].length;i++) {
alert(json['popular result'][i].term + ' points to the URL ' + json['popular result'][i].url);
}
});
});
</script>
Notice how the alert references the json object (that's your variable name), the popular result array, then [i] is the "row" in that array, and the term/url element of the object on that row.
NOTE: Running something with a ton of alerts as you're debugging is annoying. Check out console.log.
You don't need $.each and you need to loop over the array set as the value of popular result which is inside a containing object.
$.getJSON('/Controls/GetPopularSearches', function (json) {
var arr = json['popular result'];
for (var i = 0, l = arr.length; i < l; i++) {
console.log(arr[i].term);
}
});
Demo.
Check this fiddle
var jsontext =
'{"popularresult":[{"term":"Summer","url":"http://summer.com"},{"term":"Summer","url":"http://summer.com"}]}';
var getContact = JSON.parse(jsontext);
for (i = 0; i < getContact.popularresult.length; i++) {
alert(getContact.popularresult[i].term);
}
http://jsfiddle.net/ae8gd/
If you get the jsonObject as shown then
var JsonArray=json.popular; //get jsonArry
$.each(JsonArray,function(i,val){
// do logic
});
To parse json use JSON.parse();

Get variable names with JavaScript

I want to create a log function where I can insert variable names like this:
var a = '123',
b = 'abc';
log([a, b]);
And the result should look like this in the console.log
a: 123
b: abc
Get the value of the variable is no problems but how do I get the variable names? The function should be generic so I can't always assume that the scope is window.
so the argument is an array of variables? then no, there is no way to get the original variable name once it is passed that way. in the receiving end, they just look like:
["123","abc"];
and nothing more
you could provide the function the names of the variables and the scope they are in, like:
function log(arr,scope){
for(var i=0;i<arr.length;i++){
console.log(arr[i]+':'scope[arr[i]]);
}
}
however, this runs into the problem if you can give the scope also. there are a lot of issues of what this is in certain areas of code:
for nonstrict functions, this is window
for strict functions, this is undefined
for constructor functions, this is the constructed object
within an object literal, this is the immediate enclosing object
so you can't rely on passing this as a scope. unless you can provide the scope, this is another dead end.
if you pass them as an object, then you can iterate through the object and its "keys" and not the original variable names. however, this is more damage than cure in this case.
I know you want to save some keystrokes. Me too. However, I usually log the variable name and values much like others here have already suggested.
console.log({a:a, b:b});
If you really prefer the format that you already illustrated, then you can do it like this:
function log(o) {
var key;
for (key in o) {
console.log(key + ":", o[key]);
}
}
var a = '1243';
var b = 'qwre';
log({
a:a,
b:b
});
Either way, you'd need to include the variable name in your logging request if you want to see it. Like Gareth said, seeing the variable names from inside the called function is not an option.
Something like this would do what you're looking for:
function log(logDict) {
for (var item in logDict) {
console.log(item + ": " + logDict[item]);
}
}
function logSomeStuff() {
var dict = {};
dict.a = "123";
dict.b = "abc";
log(dict);
}
logSomeStuff();
Don't know if this would really work in JS... but you can use a Object, in which you can store the name and the value:
function MyLogObject(name, value) {
this.name = name;
this.value = value;
}
var log = [];
log.push(new MyLogObject('a', '123'));
log.push(new MyLogObject('b', 'abc'));
for each (var item in log) {
if (item.value != undefined)
alert(item.name + "/" + item.value);
}
Then you can loop thru this Object and you can get the name and the value
You can't access the variable names using an Array. What you could do is use objects or pass the variable names as a String:
var x = 7;
var y = 8;
function logVars(arr){
for(var i = 0; i < arr.length; i++){
alert(arr[i] + " = " + window[arr[i]]);
}
}
logVars(["x","y"]);
I had a somewhat similar problem, but for different reasons.
The best solution I could find was:
MyArray = ["zero","one","two","three","four","five"];
MyArray.name="MyArray";
So if:
x=MyArray.name;
Then:
X=="MyArray"
Like I said, it suited my needs, but not sure HOW this will work for you.
I feel silly that I even needed it, but I did.
test this.
var variableA="valor01"; <br>
var variableB="valor02";
var NamevariableA=eval('("variableA")');<br>
var NamevariableB=eval('("variableB")');<br>
console.log(NamevariableA,NamevariableB);
atte.
Manuel Retamozo Arrué

Categories