Javascript: finding a value from an object - javascript

I have the following object:
var stuff = {};
stuff["jar"] = "biscuit";
stuff["cupboard"] = "food";
Iterating through the list with an For i loop and getting the value is easy, but how would I get the key?
for (var i in stuff) {
var key = GET KEY SOMEHOW
var val = stuff[i];
}

The key is i. However, make sure that the key is in your object, not part of the prototype chain.
for (var i in stuff) {
var key = i;
if (stuff.hasOwnProperty(i)) {
var val = stuff[i];
}
}
See also:
https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

var key = i;
In Javascript's for (foo in bar) if foo is the index of an object or array and happens to be a string, it should print or assign the string when called.

You already have it:
for (var key in stuff) {
var val = stuff[key];
}

If you have the value already you may find the key by using this logic :
for (var i=0;i<numKeyValuePairs;i++)
{
if(val==key[i])
{
document.write(key[i];
}
}

Related

accessing JSON value if key is array element

suppose i receive JSON object from the server as this
{ "asdf[zxcv]": "qwer" }
how do i access asdf, zxcv, and qwer in javascript, so i can use the object this way ?
theobj.asdf[zxcv] = 'qwer'
Bracket notation is not in the JSON RFC. You can only read it as string.
var simpleObj = {
"simpleKey": "simpleValue"
}
console.log(simpleObj)
var advObj = {
"advKey[1]": "advValue"
}
console.log(JSON.parse(advObj)); // SyntaxError
console.log(advObj.advKey[1]) // TypeError
console.log(advObj["advKey[1]"]) // can only read as string
You would need to refactor the source JSON into something more meaningful so you can access the values in regular JavaScript way.
Run the following snippet to check how you can solve the issue:
var x = '{ "asdf[zxcv]": "qwer" }';
var y = JSON.parse(x);
var result = Object.keys(y).reduce(function(result, key) {
var parentKey = key.substring(0, key.indexOf("["));
var innerKey = /[a-z]+\[([a-z]+)\]/i.exec(key)[1];
if (!result.hasOwnProperty(key))
result[parentKey] = {};
result[parentKey][innerKey] = y[key];
return result;
}, {});
document.getElementById("structure").textContent = JSON.stringify(result);
var zxcv = result["asdf"]["zxcv"];
document.getElementById("someValue").textContent = zxcv;
<h2>Refactored data structure as nested objects:</h2>
<div id="structure"></div>
<h2>Accessing some value: result["asdf"]["zxcv"] or result.asdf.zxcv</h2>
<div id="someValue"></div>
It's all about creating nested objects to represent the associative keys in the source JSON properties representing a conceptual associative array...
This is one of the way to access all elements without reconstructing object.
jQuery.each(JSON.parse('{ "asdf[zxcv]": "qwer" }'), function(index, value) {
var i = index;// i = "asdf[zxcv]"
var v = value;// v = "qwer"
var iOfInnerValue = (/\[(.*?)\]/g).exec(i)[1];// innerValue = "zxcv"
var iOfOuterValue = index.replace("["+(/\[(.*?)\]/g).exec(i)[1]+"]",""); // outerValue = "asdf"
});
You'll need to assign the data to a variable and then you can use Object keys to get the key which is the part before the :. Here's an example.
var j = { "asdf[zxcv]": "qwer" };
console.log(Object.keys(j)); //["asdf[zxcv]"]
console.log(j); //{asdf[zxcv]: "qwer"}

Setting array key value pair JavaScript

So, I am having an issue and for the life of me I cannot seem to resolve it. It seems very basic, but I just cannot understand for the life of me why this code is not working.
My issue is, I am assigning a key value pair to an array, but the values DO NOT get assigned. Is it a variable scope issue?
Here is my code
function getcookie(cookiename){
var mycookies = []; // The cookie jar
var temp = document.cookie.split(";");
var key = "";
var val = "";
for(i=0;i<temp.length;i++){
key = temp[i].split("=")[0];
val = temp[i].split("=")[1];
mycookies[key] = val;
}
return mycookies[cookiename];
}
Trim your key because cookie strings look like this:
"__utma=250730393.1032915092.1427933260.1430325220.1430325220.1; __utmc=250730393; __utmz=250730393.1430325220.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); clicks=22; _gat=1; _ga=GA1.2.1032915092.1427933260"
so when you split on ; there will be an extra space before some of the key names.
function getcookie(cookiename){
var mycookies = []; // The cookie jar
var temp = document.cookie.split(";");
var key = "";
var val = "";
for(i=0;i<temp.length;i++){
key = temp[i].split("=")[0].trim(); // added trim here
val = temp[i].split("=")[1];
mycookies[key] = val;
}
return mycookies[cookiename];
}
Demo: JSBin
mycookies should be populated assuming temp.length is greater than 0. Your return value is always going to be undefined; mycookies[cookiename] is never assigned a value.
Try adding console.log(mycookies) just before your return statement.
Mycookies should be an Object, not an Array.
var mycookies = {};
JavaScript arrays are not associative arrays, only possible index values are numerical, starting with 0 and ending at array.length - 1. What you might have seen in examples before or used in another language before was JavaScript object, which does, in fact, behave as an associative array. You can access object values by object['key'] or as object.key. The first is used only when accessing key using a variable or a key which includes illegal characters, i.e. some-key, otherwise it's recommended to use dot access, as illustrated in second example.
Therefore your mycookies variable should be an object, not an array.
If you change your line var mycookies = []; to var mycookies = {};, i.e. change it from empty array to empty object, the remaining code should work as you expected.
Here is an example snippet for fixed code, I added a mock cookies string so it can work reliably:
var mockCookies = "a=1;b=2;c=3";
function getcookie(cookiename){
var mycookies = {}; // The cookie jar
var temp = mockCookies.split(";");
var key = "";
var val = "";
for(i=0;i<temp.length;i++){
key = temp[i].split("=")[0];
val = temp[i].split("=")[1];
mycookies[key] = val;
}
return mycookies[cookiename];
}
function printCookie(name) {
alert(getcookie(name));
}
<button onclick="printCookie('a')">Get a</button>
<button onclick="printCookie('b')">Get b</button>
<button onclick="printCookie('c')">Get c</button>
My friend, you are a little confused (maybe you have programmed in PHP) because in JavaScript, an Array is not a associative key : value object, it is an indexes based object. But what you looking for is an Object Literal
function getcookie (cookiename){
var i, max, keyvalue, key, val,
cookiesObj = {}, //empty object literal
cookiesArr = document.cookie.split(";");
for(i=0, max=cookiesArr.length; i<max; i+=1) {
keyvalue = cookiesArr[i].split("=");
key = keyvalue[0].trim();
val = keyvalue[1].trim();
cookiesObj[key] = val;
}
return cookiesObj[cookiename];
}
But you can refactor your code:
function getcookie (cookiename) {
var cookie = "",
cookies = document.cookie.split(";");
cookies.forEach(function (item) {
var keyvalue = item.split("="),
key = keyvalue[0].trim(),
val = keyvalue[1].trim();
if (key === cookiename) {
cookie = val;
return false; //exit from iteration
}
});
return cookie;
}

Create object with key:value in one line

I need implement this in one line, if possible:
I have an object
var object1 = {};
object1['key_1'] = "value_1";
object1['key_2'] = "value_2";
object1['key_3'] = "value_3";
I need pass to an function one item from object (not only value ), key - only string value
for (var key in object1)
FunctionTemp({key:object1[key]}); // - this don't work as I need, and eval() method I don't want
maybe there is something like this
FunctionTemp((new {})[key]=object1[key]) - its don't work!!! :)
Since you really want it in one line you can do it like this:
var temp;
for (var key in object1)
FunctionTemp(((temp = {}) && (temp[key] = object1[key]))? temp: null);
but I think it is no longer readable as it is, the most ideal solution would be to break it down into several lines.
var temp;
for (var key in object1) {
temp = {};
temp[key] = object1[key];
FunctionTemp(temp);
}
What you're asking for is not possible without a function.
What you want to do is this:
var key = getKey(); //some means of determining a key dynamically
var val = getVal(); //some means of determining a value dynamically
var obj = {};
obj[key] = val;
this.doSomething(obj);
What you need is another method that assembles the object based on the dynamic key/value.
this.doSomething(_.object([[getKey(), getVal()]]));

string as object reference to object variable

var string = 'object.data.path';
That's a string that resembles a path to variable.
How can I return the corresponding variable from that string?
Something like transforming the string into return object.data.path;
The thing behind this is that the string could be much longer (deeper), like:
var string = 'object.data.path.original.result';
function GetPropertyByString(stringRepresentation) {
var properties = stringRepresentation.split("."),
myTempObject = window[properties[0]];
for (var i = 1, length = properties.length; i<length; i++) {
myTempObject = myTempObject[properties[i]];
}
return myTempObject;
}
alert(GetPropertyByString("object.data.path"));
this assumes that your first level object (in this case called object is global though.
Alternatively, although not recommended, you could use the eval function.
Assuming you don't want to just use eval you could try something like this:
function stringToObjRef(str) {
var keys = str.split('.'),
obj = window;
for (var i=0; i < keys.length; i++) {
if (keys[i] in obj)
obj = obj[keys[i]];
else
return;
}
return obj;
}
console.log(stringToObjRef('object.data.path.original.result'));
Uses a for loop to go one level down at a time, returning undefined if a particular key in the chain is undefined.

Access dynamically named JavaScript Objects?

I have a JS Object:
var testObj = new Object();
that has a property called volume1, so
testObj.volume1
has a value. How would I go about accessing that property by using something along the lines of
testObj.volume + "1"
To give it more context, the object actually has more properties, like
testObj.volume1, testObj.volume2 and testObj.volume3
and I want to access them using some iteration. I've tried playing with the window[] element, but have had not much success.
Thanks!
testObj["volume" + 1]
but you actually want an array here
testObj.volume = [...]
testObj.volume[1] = whatever
off topic it is considered better pratice to do
var testObj = {};
instead of
var testObj = new Object();
Use something in the fashion of testObj["volume" + "1"] ;)
The notations object.property and object["property"] are (almost) equivalent in javascript.
You can use for loop with in operation.
for(var PropName in testObj) {
var PropValue = testObj[PropName];
....
}
In case, you only want the property with the name started with 'value' only, you can also do this:
for(var PropName in testObj) {
if (!/^value[0-9]$/.match(PropName))
continue;
var PropValue = testObj[PropName];
....
}
OR if the number after the 'value' is always continuous you can just use a basic for loop.
for(var I = 0; I <= LastIndex; I++) {
var PropName = "value" + I;
var PropValue = testObj[PropName];
....
}
Hope this helps.

Categories

Resources