OOP get this key value of object array - javascript

So close to nailing this but falling at the last hurdle... Need some clarification.
Basically, I want to load in the array value of a key in a given object as a variable, if other variable strings match.
Perhaps it's better if I give it some context:
js:
var ArraysObject = {
"new" : [
"http://productPageBanners/UK/2new/c0bkn201001u0000.jpg",
"http://productPageBanners/UK/2new/h0ihd60100000001.jpg",
"http://productPageBanners/UK/2new/l0flj20100000001.jpg",
"http://productPageBanners/UK/2new/m0lrt60100000001.jpg",
"http://productPageBanners/UK/2new/p0gps50106000001.jpg"
],
"knives" : [
"http://productPageBanners/UK/3aknives/c0bkn201001u0000.jpg",
"http://productPageBanners/UK/3aknives/n01pl20100000001.jpg"
]
};
var url = jQuery(location).attr('href'); // get the current url, outputs URL
var icatRef = url.split("/")[4]; // capture the icatRef from url, outputs ==>"knives"
// Get properties on the object ArraysObject as an array
var icatTitlesInObject = Object.keys(ArraysObject); // outputs the keys in object, i.e ==> ["new","knives"]
Then I want to check that if the indexOf that array is equal to the icatRef (pulled from the URL), then create a new variable which stores the relevant array from the correct key.
Something like:
if (icatsArray.indexOf() == icatRef) {
var currentarraytorandomise = ArraysObject.keys.this};
// if "knives" is the icatRef then currentarraytorandomise ==> [
// "http://productPageBanners/UK/3aknives/c0bkn201001u0000.jpg",
// "http://productPageBanners/UK/3aknives/n01pl20100000001.jpg"
// ]
However that last bit is wrong because currentarraytorandomise is undefined.
I hope that's clear! Quite new to OOP.

You're using indexOf incorrectly, try something like this:
var currentarraytorandomise, index = icatsArray.indexOf(icatRef);
if (index >= 0) {
currentarraytorandomise = ArraysObject[icatsArray[index]];
}
But you could just try to get the array directly:
ArraysObject[icatRef]
Without extracting keys or anything. If icatRef doesn't exist, you'll get undefined.

Related

How to call items from an array inside a function

I have a function "zoom" which takes the following format:
zoom( [a,b,c,d....], [a,b,c,d...] );
I also have a for loop which gets me the values that need to go into the zoom array:
ABC.getAggregation("V")[0].getItems().forEach( function (item) {
var a = item.getPosition().split(";")[0];
var b = item.getPosition().split(";")[1];
ABC.zoom( [...], [...] );
});
How can I add variables a and b into the arrays of function zoom?
All variable a's must go into the first array and all variables b must go into the second.
Example:
ABC.getAggregation("V")[0].getItems()
//returns a list of 3 objects
item.getPosition()
//returns e.g "0,0,0" for the first item and so on (for all 3)
item.getPosition().split(";")[0] = "0"
//now i want to add this to the zoom function.
var a = item.getPosition().split(";")[0];
//this produces three string values "14.5". "4", "8.64"
var b = item.getPosition().split(";")[1];
//this produces three string values "5.7","6.8","1"
Now, I want to put these string values into zoom like this:
ABC.zoom( [14.5. 4, 8.64], [5.7,6.8,1] );
//note - they're not strings anymore.
How can I achieve this result?
You cannot execute the call to ABC.zoom() inside the .forEach() loop, since you'll only get the whole data set once all iterations have been executed.
I think you need something along those lines:
var zoomA = [],
zoomB = [];
ABC.getAggregation("V")[0].getItems().forEach( function (item) {
var a = item.getPosition().split(";")[0];
var b = item.getPosition().split(";")[1];
zoomA.push(Number(a));
zoomB.push(Number(b));
});
ABC.zoom(zoomA, zoomB);
Please let me know if I somehow misunderstood what you are trying to do.
Split return an array of strings, so item.getPosition().split(";")[0]; will return a string, not three strings. You need to split it again with , delimiter, parse the result array to int (you can use map function) and pass to zoom function.

How would I go about using a multidimensional array variable in javascript

Hi there before I start I did try looking through the search about writing variables so if this has been asked and answered then I do apologise but this is baffling me ....
So here goes ..
example of what I am talking about
var i = e[ab]
var n = e[cd][ef]
var t = e[cd][gh]
I know that when I want var i I can put e.ab but how would I go about writing var n and var t
So assuming your object looks like this (based on your description, it sounds like you want to access an object which is the property of another object), and you want to access them through the indexer properties (which would be a property of a property).
var e = {
ab : "variableOne",
cd : {ef:"ef object"},
gh : {ij:"ij object"},
}
var i = e["ab"]
//if these are properties, then you need to add quotes around them
//to access a property through the indexer, you need a string.
var n = e["cd"]["ef"]
var t = e["gh"]["ij"]
console.log(i);
console.log(n);
console.log(t);
console.log("this does the same thing:")
console.log(e.ab);
console.log(e.cd.ef);
console.log(e.gh.if);
In your example the object would look like
//e is the parameter, but I show it as a variable to show
// it's relation to the object in this example.
e = {
now_playing: {artist:"Bob Seger"; track:"Turn the Page"}}
}
this is different than an array of arrays:
var arr = [
['foo','charlie'],
['yip', 'steve'],
['what', 'bob', 'jane'],
];
console.log(arr[0][0]); //foo
console.log(arr[0][1]); //charlie
console.log(arr[1][0]); //yip
console.log(arr[1][1]); //steve
console.log(arr[2][2]); //jane
https://jsfiddle.net/joo9wfxt/2/
EDIT:
Based on the JSON provided, it looks like parameter e in the function is assigned the value of the item in the array. With your code:
this line will display: "Rock you like a hurricane - Nontas Tzivenis"
$(".song_title .current_show span").html(e.title);
and this line will display: "Rascal Flatts - Life is a Highway".
$(".song_title .current_song span").html(e.np);
If it's not displaying you might want to double check your JQuery selectors. This ".song_title .current_song span" is selecting it by the classes on the element.
I think you are in need of a bit of a refresher on basic JavaScript syntax. Here's how you can assign an "empty object" to a variable, then start to assign values to it's properties:
e = {}
e.ab = {}
e.cd = {}
e.cd.ef = "data"
or you can use the associative array syntax for property access:
e = {}
e["ab"] = {}
e["cd"] = {}
e["cd"]["ef"] = "data"
You see the latter is using the object e like a two-deep associative array. Is that what you are looking to do?
JavaScript is not strongly typed. So an Array "a" could contain objects of different types inside.
var a = [ "a value", [1, 2, 3], function(){ return 5 + 2;}];
var result = a[0]; //get the first item in my array: "a value"
var resultOfIndexedProperty = a[1][0]; //Get the first item of the second item: 1
var resultOfFunc = a[2](); //store the result of the function that is the third item of my array: 7
Hope this helps a little.

Delete and Add object at same index in Nested Object

Object :
var userData = {
"a1":{"a":"1"},
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
};
I need to delete Object with key "a1" and place a new object i.e. "f6" at same place.
i.e.
userData["f6"] = userData["a1"];
userData["f6"].new = "true";
delete userData["a1"];
Output:
userData = {
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
"f6":{"a":"1", new:true},
};
Expected O/p:
var userData = {
"f6":{"a":"1", new:true},
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
};
Thanks in Advance..
In Javascript, objects have no specific order for their properties. When you see them as a JSON, the properties are shown in the same order they where declared or added. To mantain a specific order, you may do changes in your object and implement an Array.

JavaScript: Access object variable inside nested array

How would I access ArrayObjectVariable inside
ArrayObject[0]? I know if you don't have a [ ] around it its as simple
as ArrayObject[0].ArrayObjectVariable?
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{ ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0]???);
I didn't realize the whole "ArrayObject[0][0].ArrayObjectVariable" thing. Thanks for the replies. I was trying it with just one ("[0]") instead of two ("[0][0]"). My second question is, what is the second "[0]" for? I just tried making multiple variables and it still used "[0][0]" ? So what's the second "[0]" controlling?
Third question? I noticed that it created a variable outside the array when I did that? When I change the value of the variable in the array, it has no effect on the one outside of it? Likewise, when I change the value of the variable outside of the array it has no effect on the one inside it. Is there a way to create the array without creating a variable outside of the array with the same name? Thanks :)
OK figured it out :) Just make the Object in the array without the "[ ]". The whole point of this was to figure out how to access nested items but I got it now. Didn't realize how to make them without the "[ ]". Example for those of you struggling like I was:
// create variables that we are going to use in Array Objects. Or make a function with the values.
var ATV1 = 'AyTeeVeeOne', ATV2 = 'AyTeeVeeTwo', ANV1 = 'AyEnVeeOne';
var ATV3 = 'AyTeeVeeThree', ATV4 = 'AyTeeVeeFour', ANV2 = 'AyEnVeeTwo';
// Make an Array
var ArrayObject;
ArrayObject = [{}];
// Insert variables into Array object(s).
ArrayObject[0] = {ArrayTestObject1 : { ArrayTestValue1:ATV1,
ArrayNestedObject1:{ ArrayNestedValue1:ANV1 },
ArrayTestValue2:ATV2
}};
ArrayObject[1] = {ArrayTestObject2 : { ArrayTestValue3:ATV3,
ArrayNestedObject2:{ ArrayNestedValue2:ANV2 },
ArrayTestValue4:ATV4
}};
// Access Array Object Variables
alert(ArrayObject[0].ArrayTestObject1.ArrayTestValue1) // Example 1
alert(ArrayObject[1].ArrayTestObject2.ArrayNestedObject2.ArrayNestedValue2) // Example 2
ArrayObject[0][0].ArrayObjectVariable
You have an array for the value of ArrayObject[0], so treat it like any other array.
use this:here you have ArrayObject as array and you are creating index as zero to the array and in that on zeroth place ArrayObjectVariable key resides.
<script>
var ArrayObjectVariableValue = 'AyOhVeeVee';
var ArrayObject = []
ArrayObject[0] = [{
ArrayObjectVariable : ArrayObjectVariableValue }];
alert(ArrayObject[0][0].ArrayObjectVariable);
</script>

Store values in javascript object with same keys

I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];

Categories