Javascript - Get the associative array key value - javascript

I have an object with one key value as given below -
var a = {};
a.x = "randomvalue";
My requirement is to get access the value "randomvalue", but the catch is I dont know that the property name is "x".
Simplest way to get the value??

Try:
var v, i;
var a = {};
a.x = "randomvalue";
for (x in a) {
if a[x] === "randomvalue" {
v = x;
i = "randomvalue";
}
}
Then v contains the object key and i contains the object value (although you don't really need it).
Or, if you know the value index:
var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'

Related

manipulate the object value without knowing its key

I have an object obj and I want to manipulate it's value, but I don't want to write the value hard-coded something like below, is there any better alternative to this below approach
let obj = {a:{x:0}, b:{y:0}};
obj.a[Object.keys(obj.a)[0]] = 1;
console.log(obj);
I suppose you want to loop through them and have different values for x, y or whatever the key is
let obj = {
a: {
x: 0
},
b: {
y: 0
}
};
keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
key2 = Object.keys(obj[keys[i]])[0];
// instead of some_value inject an array of values
obj[keys[i]][key2] = 'some_value';
}
console.log(obj);
I have created a generic function where you can set the value of key without knowing the property names of inside object.
You can call the function with required key and value and get the desired result.
let obj = {a:{x:0}, b:{y:0}};
function assignValue(key, value) {
obj[key][Object.keys(obj[key])] = value;
}
assignValue('a', 1)
console.log(obj)
let objMultipleInnerKeys = {a:{x:0, z:2}, b:{y:0}};
function assignValueMultipleInnerKeys(key, innerKey, value) {
objMultipleInnerKeys[key][innerKey] = value;
}
assignValueMultipleInnerKeys('a', 'x', 1)
console.log(objMultipleInnerKeys)

Javascript dynamic nested objects

I was looking into how to create a dynamic nested objects from a string, for example, a string "obj1.obj2.obj3.obj4", how do you turn that into nested objects with the same order.
I googled around and i found this nice and clean code, but i did not understand how it worked, and there was no explanation on the page where it was written, can someone explain how this works please?
here is the code:
var s = "key1.key2.key3.key4";
var a = s.split('.');
var obj = {};
var temp = obj;
for (var k =0; k < a.length; k++) {
temp = temp[a[k]] = {};
console.log(temp);
}
console.log(obj);
why is there a var temp = obj?
what does this line do?:
temp = temp[a[k]] = {};
also, the console.log(temp) inside the loop always logs an empty object {}, why?
Thanks for the feedback!
why is there a var temp = obj?
obj is a variable to hold the completed object. temp is a variable to hold each intermediate step of the object being built. temp starts out with the same value as obj so that the first iteration of the loop adds on to obj.
what does this line do?:
temp = temp[a[k]] = {};
Assign an empty object to a property in temp with the name a[k], where a[k] is one of the values in a.
Assign that new empty object to temp.
This could be written separately as two lines:
temp[a[k]] = {};
temp = temp[a[k]];
also, the console.log(temp) inside the loop always logs an empty object {}, why?
Because the previous line assigns an empty object to temp.
Your question boils down to this (comments inline)
var x = {};
var y = x;
y[ "a" ] = {}; //reference to x stays so x also becomes { "a": {} }
y = y["a"]; //now y effectively becomes {} but has the same reference to y["a"] as assignment works right to left hence property `a` is becomes non-enumerable and hence shadowed.
console.log( "First Run" );
console.log( y ); //prints {}
console.log( x ); //prints { "a": {} }
y[ "a" ] = {}; //y still has a non-enumerable property `a`
y = y["a"]; //same as above y = y["a"], y again becomes {}
console.log( "Second Run" );
console.log( y ); //prints {} again
console.log( x ); //prints { "a": { "a": {} } }
Outputs
First Run
{}
{ "a": {} }
Second Run
{}
{ "a": {
"a": {} } }
Have added comments in code, hope it will be useful
var s = "key1.key2.key3.key4";
//split the string by dot(.) and create an array
var a = s.split('.');
//Creating an empty object
var obj = {};
var temp = obj;
//looping over the array
for (var k = 0; k < a.length; k++) {
//a[k] will be key1,key2,key3....
// temp is an object,square bracket is use to create a object key
// using a variable name
// variable name here is key1,key2....
//temp[a[k]] will initialize an empty object
temp = temp[a[k]] = {};
console.log(temp);
}
console.log(obj);
It seems where you are iterating the array, in that temp object is newly creating and assigning key to obj.
temp = temp[a[k]] = {};
above line simply assigns a[index] value as a key to the new object and as a reference to obj the nested object is created.
for your question,
why is there a var temp = obj?
it copies obj object into temp variable
also, the console.log(temp) inside the loop always logs an empty object {}, why?
since you are recreating an empty object (or reassigning).

How to write the key(passed in as an argument to the function) in the js object dynamically?

temp = temp[array[i]] = {name:value};
In the above snippet the name is actually a parameter to my function having a value first_name.
Here's the function.
function createHierarchy(obj, group, name, value){
console.log("group = "+group+"\nname ="+name)
var array = group.split(".");
var temp = obj;
var len = array.length;
for(var i = 0; i < len; i++) {
if(temp[array[i]] === undefined)
temp = temp[array[i]] = {name:value};
else
temp = temp[array[i]][name] = value;
}
return obj;
}
The object being dumped has the key name equal to the identifier passed not its dynamic value which was "first_name" .
What am i missing. Let me know if i should update something.
Actual output
name: "cafebabe"
Expected output
first_name : "cafebabe"
FYI
Call this function like
createHierarchy({}, 'personal_details', 'first_name', 'cafebabe')
This piece of code is incorrect, you can't use name as variable in a default value like that:
if(temp[array[i]] === undefined)
temp = temp[array[i]] = {name:value};
else
temp = temp[array[i]][name] = value;
Replace that with:
temp[array[i]] = temp[array[i]] || {}; // If `temp[array[i]]` doesn't exist, add it.
temp = temp[array[i]][name] = value; // Assign the `value`.
JavaScript does not allow variables to be used as object keys, in object literals. In this example:
{ name: value }
JavaScript interpreters will never look for a name variable. It will just use "name" as the key.
The only way to use variables as object keys, is via the bracket notation:
myObject[name]

Returning variable name from array?

Is it possible to return a variable name from an array?
I have an array with 5 variables. Each variable is assigned a numeric value.
I am trying to find the highest value in the array and then alert its variable name, or possibly use that variable to do things with it.
var vara = 0; //resultA
var varb= 0; //resultB
var varc= 0; //resultC
var vard= 0; //resultD
var vare= 0; //resultE
function showResults() {
var buckets = [vara, varb, varc, vard, vare];
var largest = Math.max.apply(Math, buckets);
alert(largest);
}
The above code alerts the value of largest, but I want to find the corresponding variable, for instance vara instead of 3
No, it is not. If you want to associate some name with value, thats what dictionaries for.
var obj = {"name": 123, "name2": 234}
obj.name3 = 345; // assign 345 to name3
var valueOfName3 = obj.name3; // get name3
If you want to get the largest value in this object (by akonsu):
var largest = null;
var keyOfLargestVal = null;
for(var k in obj) { var v = obj[k];
if (largest === null || v > largest){
largest = v; keyOfLargestVal = k;
}
}

Javascript: Loop through unknown number of object literals

I have a list of objects all named in this fashion:
var p1 = {};
var p2 = {};
p1.name = "john";
p1.hobby = "collects stamps";
p2.name = "jane";
p2.hobby = "collects antiques";
I know how to loop through p1 and p2 to collect the properties, provided I know how many of these p object literals there are. Here's my problem, I don't always know how many of these p object literals there will be. Sometimes it goes up to p2, sometimes it goes up to p20.
Is there a way to loop through objects if I know they all share the same prefix?
Edit: I can't change how I'm getting the list of objects. It's given to me in that format...
If we make the following assumptions:
The objects are global
The number suffixes are sequential
...then the following works:
for (var i = 1; window["p" + i] !== undefined; i++) {
console.log(window["p" + i]); // loop over each object here
}
You should have them in an Array referenced by a single variable.
var p = [];
p.push({
name:"john",
hobby:"collects stamps"
}, {
name:"jane",
hobby:"collects antiques"
});
Then you'd loop the Array, and enumerate each object...
for( var i = 0; i < p.length; i++ ) {
for( var n in p[i] ) {
console.log( p[i][n] );
}
}
EDIT:
It seems from a comment that these may be arriving as individual variable.
If they're global variables, and if they always have the same p1 naming, then you can access them as properties of the global window object.
var obj;
for( var i = 1; obj = window['p' + i]; i++ ) {
if( typeof obj === 'object' ) {
for( var n in obj ) {
console.log( obj[n] );
}
}
}
This loop will run until a p(n) global returns a falsey value.
So as long as a truthy value is found, and its typeof is 'object', you'll iterate that object.
If you have all your data stored in a variable , or a few variables you can push it into the array.
var data = "....JSON";
var a = [];
a.push(data);
Push keeps adding stuff into the array in basic sense.
You could also pop to remove the last pushed data.
Take a look at the other methods here:
http://www.w3schools.com/jsref/jsref_obj_array.asp
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
Why don't you just store them all in one top-level object literal? It will make it easier to enumerate through them.
EG:
var MyObj = {
p1: {},
p2: {}
};
etc..
[edit]
If they are local vars, are you can't change the format of this data, you might have to use eval.
Don't shoot me:
var p1 = {};
var p2 = {};
p1.name = "john";
p1.hobby = "collects stamps";
p2.name = "jane";
p2.hobby = "collects antiques";
var found = true, c = 1;
while(found) {
try {
var obj = eval('p' + c);
c++;
console.log(obj);
} catch(e){
found = false;
}
}
I don't suggest using this, I suggest changing the format of the data you are receiving, but this is one possible solution.

Categories

Resources