Accessing nested JavaScript objects with variables - javascript

I want to access (get/set) a nestedJS object with a variable.
For example, static it would look like that:
$obj.children.12.children.32.Name; // Returns "Foo"
Now I have an "Route" array (or whatever is easy too handle):
["children",12,"children",32,"Name"]
And want to get the value of the object.
Like I read here on Stackover, there is an very easy way to do it (Solution 2).
But, now I want to change the value for the passed key/route. Is there any way to do that?
Thank you very much!
Edit:
I can use jQuery/Angluar-Features, if it helps me.

Borrowing code from the accepted answer on the post you've linked to, we can trivially make a getter:
function getFromPath(obj, pathArray) {
var res = obj;
for (var i=0; i<pathArray.length; i++) { res = res[pathArray[i]]; }
return res;
}
We call this with getFromPath($obj, ["children",12,"children",32,"Name"]);.
Since you want to transform this getter function into a setter, you want to set a property on the second-to-last object. We can do this by stopping the loop one iteration early and then performing set with the final property name on the object:
function setToPath(obj, pathArray, valueToSet) {
var res = obj;
// note the `length - 1` here: we don't go to the end of the path
for (var i=0; i<pathArray.length - 1; i++) { res = res[pathArray[i]]; }
// res is now the second-to-last object in the path,
// and we'll set the final value as a property on the object
var finalKey = pathArray[pathArray.length-1];
res[finalKey] = valueToSet;
}
We call this with setToPath($obj, ["children",12,"children",32,"Name"], "Dana");.
Alternatively, if you wanted to do this with just a getter, you could shorten your path by one item and perform the set on the result from the getter:
var secondToLast = getFromPath($obj, ["children",12,"children",32]);
secondToLast["Name"] = "Dana";

Related

Get all values of variable using JS

So in my js code I have some global variable that changes its value several times, for example
var x = 0;
...
x = 10;
...
x = 5;
Is there any possibility to get "history" of x without saving its value in other variables? Like, is there some function to detect that at some point of time x was equal to 10?
No, once a value is assigned to a variable, that variable's previous value is overwritten. It isn't retained anywhere. (If it were, it would be a nightmare for memory management.)
You could make an object property that retained a history if you wanted, by using a setter function; rough example:
var obj = {
_fooValue: undefined,
fooHistory: [],
set foo(value) {
this.fooHistory.push(this._fooValue);
this._fooValue = value;
},
get foo() {
return this._fooValue;
}
};
obj.foo = 0;
obj.foo = 5;
obj.foo = 42;
console.log(obj.fooHistory);
In that example, the history doesn't contain the current value, just the previous ones, and it stores the current value in another object property which means code could bypass the setter. There are lots of tweaks you could do. If you thought it was important, you could lock it down more:
var obj = (function() {
// These two vars are entirely private to the object
var fooHistory = [];
var fooValue;
// The object we'll assign to `obj`
return {
set foo(value) {
fooHistory.push(fooValue);
fooValue = value;
},
get foo() {
return fooValue;
},
get fooHistory() {
// Being really defensive and returning
// a copy
return fooHistory.slice(0);
}
}
})();
obj.foo = 0;
obj.foo = 5;
obj.foo = 42;
console.log(obj.fooHistory);
You can use variable like array and unshift next value to this array. And to use it take first element:
var x = [];
...
x.unshift(10);
...
x.unshift(5);
var currentX = x[0];
var allValues = x;
Yes there is. Using the Time Travelling debugging in Microsoft Edge browser. Check this out.
I'm not JS specialist, but as common idea for any OOP language, I would suggest to create special class for x (inherited from Integer in your example), which has overriden setter and some history array list. So, when you set a new value it stored in your history.
You need change only the variable type, not the code, which works with that. I also don't think there is some standard solution for this in any language. Probably, some dynamic introspectors, but those would be even more complex than my idea.

Javascript - Custom arrays not working

Please check the code below -
custom_array.push(...) is working
but
custom_array[i] = "n"
is not working.
There are a couple more things which i am not sure why it is not working. Please note the comments with "?" which is not working. Please refer fiddle - http://jsfiddle.net/vc0bbm3d/
The reason that setting items using bracket syntax doesn't work for your object inheriting an array, is that it's not actually an array.
An array has special code for handling property assignment (which is what you do with the bracket syntax) when the property name is an integer. If the index is outside the current length, the length property is adjusted.
When you assign a value to a property in your object, there is no special code to handle the length. The property is just assigned as usual, and the length is never adjusted. As the object already has code for handling what's happening when you use the bracket syntax, the array that it inherts never comes into play.
For the bracket syntax to work in that way, the object has to be an actual array.
try
ar[3] = 2;
ar.length =4
That way it knows you have added something.
Here's an example of what I mean when I say create a layer around the default array object to extend functionality:
var SuperArray = function(){
this.arr = Array.prototype.slice.call(arguments);
};
//abstraction of default array functionality
SuperArray.prototype.set = function(index, value){
this.arr[index] = value;
return this;
};
SuperArray.prototype.unset = function(index){
this.arr.splice(index, 1);
return this;
};
//extension of default array functionality
SuperArray.prototype.consoleList = function(){
var arr = this.arr;
for(var i = 0, l = arr.length; i < l; i++){
console.log(arr[i]);
};
return this;
};
var extArr = new SuperArray(1,2,3);
extArr.set(2, 25); //does array[2] = 25;
extArr.unset(1); //removes array[1]
extArr.consoleList();//console.logs all items in array
extArr.set(2, 25).unset(1).consoleList();//same thing
this simple object accepts arguments and sets them directly into an array, which we then manipulate how we wish. You can then add any utility functions that you need, check for existing array functionality, etc.

Initialize a JavaScript object "tree" to any depth, nested objects

Essentially my I am trying to initialize a JavaScript object and have it contain empty objects with a single key. For example:
getOject('one.two.three')
Would result in the object:
{one:{two:{three:''}}}
As far as I can tell, you can't initialize with dynamic key names unless you use array notation
root[dynamicKey] = 'some variable';
so I need to loop through and based on the number of args initialize each one then assign it's value but the syntax doesn't seem to let me do this in any way that I know of.
So, if it were not a loop it would be like this:
jsonifiedForm[rootKey] = {};
jsonifiedForm[rootKey][childKeys[0]] = {};
jsonifiedForm[rootKey][childKeys[0]][childKeys[1]] = $input.val();
I can't think of a way to do this, I am not typically a JS guy so it might be something simple but I couldn't find anything on Google or Stack Overflow
Thank you in advance!
This function should be what you're looking for.
function getOject(str) {
// this turns the string into an array = 'one.two.three' becomes ['one', 'two', 'three']
var arr = str.split('.');
// this will be our final object
var obj = {};
// this is the current level of the object - in the first iteration we will add the "one" object here
var curobj = obj;
var i = 0;
// we loop until the next-to-last element because we want the last element ("three") to contain an empty string instead of an empty object
while (i < (arr.length-1)) {
// add a new level to the object and set the curobj to the new level
curobj[arr[i]] = {};
curobj = curobj[arr[i++]];
}
// finally, we append the empty string to the final object
curobj[arr[i]] = '';
return obj;
}
Because JavaScript references values in variables instead of copying them "into" variables, we can make our initial value, then make a reference to it which we'll move around as we delve down in:
var getOject = function (k, s) {
// initialize our value for return
var o = {},
// get a reference to that object
r = o,
i;
// we'll allow for a string or an array to be passed as keys,
//and an optional sepeartor which we'll default to `.` if not given
if (typeof k === 'string') {
k = k.split(s || '.');
}
// do we have an array now?
if (k && k.length) {
//iterate it
for (i = 0; i < k.length; i += 1) {
// set a property on the referenced object
r[k[i]] = {};
// point the reference to the new level
r = r[k[i]];
}
}
// send back the object
return o;
}
console.log(getOject('one.two.three'));
console.log(getOject('four|five|six', '|'));
r points to the same thing that o does, initially, and as we move the reference (r) deeper into o and write to it, we're building out o as we go.
The two console.log() calls at the end output the following:
Also notice I let you pass in an array to start with if you feel like it, and made the separator a parameter so that you're not stuck with .

Javascript: How can I transform an array?

I have this on a javascript var: (it's a http returned data, and I don't know if it's an array or string - (how can we see that?) - Update: using typeof returned "string", so it's a string.
[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}]
How can we pass/transform that, into something like this:
["gggg.fa","rarar.fa"]
?
Thanks a lot,
MEM
You can figure out if is a string or an already parsed object by checking the type of your variable, e.g.:
ajax('url', function (response) {
alert(typeof response);
});
You will now figure out if it's a "string" or an Array "object".
If it's a string, you can use the JSON.parse method as #alcuadrado suggest, otherwise you can simply use the array.
Several answers suggest the use of the for-in statement to iterate over the array elements, I would discourage you to use it for that.
The for-in statement should be used to enumerate over object properties, to iterate over Arrays or Array-like objects, use a sequential loop as #Ken Redler suggests.
You should really avoid for-in for this purpose because:
The order of enumeration is not guaranteed, properties may not be visited in the numeric order.
Enumerates also inherited properties.
You can also use the Array.prototype.map method to meet your requirements:
var response = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
var array = response.map(function (item) { return item.nomeDominio; });
// ["gggg.fa", "rarar.fa"]
This question is strongly related with this one.
I would suggest reading my answer there, as it would really help; and with a little variation, it would just work:
var responseString = '[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}]',
responseObject = JSON.parse(responseString),
nombresDeDominio = [];
for(var i in responseObject) {
nombresDeDominio.push(responseObject[i].nomeDominio)
}
Suerte!
Assuming your data always looks like that, you can do something like this:
var foo = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
var newarr = [];
for ( var i=0,j=foo.length;i<j;i++ ) {
newarr.push( foo[i]['nomeDominio'] );
}
Here's a working fiddle.
function transform(array, f) {
var ret = [];
$.each(array, function(index) {
var v = f.call(this, index);
if(v) {
ret.push(v);
}
});
return ret;
}
var result = transform(
[{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}],
function() { return this.nomeDominio; }
);
alert(result.toString());
it's a http returned data, and I don't
know if it's an array or string
It's JSON, and you can use it directly in JavaScript.
If you transform it into your array, you will lose the association key / value ; are you sure it's what you want ?
Okay, firstly to get the type of a "thing", use the "typeof" operator (note that the type of an array is an object, not 'array'!):
var a = "string";
var b = 1;
var c = new Array();
alert(typeof(a)); // string
alert(typeof(b)); // number
alert(typeof(c)); // object
To get at the values in the associative array (assuming it is one), you can just loop through it, like so:
var d = [{"nomeDominio":"gggg.fa"},{"nomeDominio":"rarar.fa"}];
d["bob"] = "alice";
d["gary"] = "stephen";
for(var key in d) {
alert(d[key]);
}

Remove element from Javascript associative array using array value

I am trying to remove an element from a Javascript associtive array using the value to find it, but I am having trouble. I have tried splice and JQuery's grep method and neither have worked for me. This is what I currently have.
var array_path = new Array();
function bulk_upload(){
var temp_array = new Object();
for (var i = 1; i<8; i++){
temp_array[i] = $('#path' + i).val();
if(temp_array[i]!='' && temp_array[i]!=null){
array_path['path' + i] = $('#path' + i).val();
}
}
process_txt();
}
function process_txt(){
//alert(array_path.indexOf(full_path)); //returns nothing
var removed_element = array_path.splice(getKey(array_path), 1);
//array_path = $.grep(array_path, function(val) { return val != full_path; });
alert(removed_element);//return nothing, just blank alert box
}
function getKey(data) {
for (var prop in data)
return prop;
}
The way to do this is to use the delete operator.
delete array_path[getKey(array_path)]
Some Background Information
In JavaScript, almost everything descends from Object.prototype. JavaScript, being an open and dynamic language allows you to create/modify properties of objects by simple assignment. This is very similar to what an associative array -- a structure that contains keyed values.
Under the hood an array is just an object that descends from Array.prototype with numeric keys and a special property called length. The length property just returns one greater than the highest numeric property. In essence, an Array is an object with different semantics.
If you're wanting an associative array then Array is not the object you want to descend from. You would want to descend directly from Object. There are two ways to do that, you could either use the new operator or an empty object literal. The syntax for both is below:
var o = new Object();
var o = {};
The second is preferred since it's a little bit more concise.
I wrote a blog post about this a while back, have a look if you want a little bit more info.
There is no such thing in JavaScript as an "associative array" per se. The data structure which corresponds to this concept is simply a JavaScript Object.
Of course, a JavaScript Array (like essentially everything in JavaScript) is an Object, but one with additional capabilities. So you can use an Array as a key-value map, but it's really not the correct structure for that.
To remove a key from an Object, you just do something like this:
var myObj = {};
var myKey = "blah";
myObj[myKey] = 1234; // Adds or updates value for "blah" to 1234.
delete myObj[myKey]; // Removes key-value pair for "blah".
Have you tried delete hash.someKey; ?
You can give your object a remove method, or use apply or call to use another object's remove method, if defined.
function myObj(members){
for(var p in members) this[p]= members[p];
}
myObj.prototype.remove= function(val){
for(var p in this){
if(this[p]=== val) delete this[p];
}
return this;
}
myObj.prototype.toString= function(){
var A= [];;
for(var p in this){
if(this.hasOwnProperty(p)){
A.push(p+':'+this[p])
}
}
return '{'+A.join(', ')+'}';
}
var O= new myObj({a: 1, b: 10, c: 100});
alert(O)
O.remove(10);
alert(O)
I'm not psychic, so I can only guess that you wanted to accomplish something like this:
var paths = [];
function getPaths() {
for(var i = 1; i < 8; ++i) {
var value = $('#path' + i).val();
if(value) paths.push(value);
}
}
function process() {
var firstPath = paths.shift();
// do stuff
}
getPaths();
if(paths.length) process();

Categories