Unable to get variable name from function argument value in lambda [duplicate] - javascript

I have code like this.
var key = "anything";
var object = {
key: "key attribute"
};
I want to know if there is a way to replace that key with "anything".
like
var object = {
"anything": "key attribute"
};

In ES6, use computed property names.
const key = "anything";
const object = {
[key]: "key attribute"
// ^^^^^ COMPUTED PROPERTY NAME
};
Note the square brackets around key. You can actually specify any expression in the square brackets, not just a variable.

Yes. You can use:
var key = "anything";
var json = { };
json[key] = "key attribute";
Or simply use your second method if you have the values at hand when writing the program.

On modern Javascript (ECMAScript 6) you can sorround the variable with square brackets:
var key = "anything";
var json = {
[key]: "key attribute"
};

This should do the trick:
var key = "anything";
var json = {};
json[key] = "key attribute";

Solution:
var key = "anything";
var json = {};
json[key] = "key attribute";

Recently needed a solution how to set cookies passing the dynamic json key values.
Using the https://github.com/js-cookie/js-cookie#json, it can be done easily.
Wanted to store each selected option value of user in cookie, so it's not lost in case of tab or browser shutting down.
var json = {
option_values : {}
};
$('option:selected').each(function(index, el) {
var option = $(this);
var optionText = option.text();
var key = 'option_' + index;
json.option_values[key] = optionText;
Cookies.set('option_values', json, { expires: 7 } );
});
Then you can retrieve each cookie key value on each page load using
Cookies.getJSON('option_values');

Closures work great for this.
function keyValue(key){
return function(value){
var object = {};
object[key] = value;
return object;
}
}
var key = keyValue(key);
key(value);

Well, there isn't a "direct" way to do this...
but this should do it:
json[key] = json.key;
json.key = undefined;
Its a bit tricky, but hey, it works!

Related

Use variable as property JavaScript [duplicate]

I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
var key = "happyCount";
myArray.push( { key : someValueArray } );
but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. Is there any way to set the value of the key from a variable?
Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/
You need to make the object first, then use [] to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";
var person = {[key]:"John"};
console.log(person); // should print Object { name="John"}
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also
supports computed property names. That allows you to put an expression
in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
Use this.
var key = 'a'
var val = 'b'
console.log({[key]:val})
//a:'b'
In ES6 We can write objects like this
const key= "Name";
const values = "RJK"
const obj = {
[key]: values,
}
In TypeScript, it should look something like this
let title ="Current User";
type User = {
[key:string | number | symbol]: any
};
let myVar: User = {};
myVar[ title ] = "App Developer";
console.log(myVar)// Prints: { Current User:"App Developer"}
let key = "name";
let name= "john";
const obj ={
id:01
}
obj[key] = name;
console.log(obj); // output will {id:01,name:"john}
Use square brackets shown it will set as key
The Reality
The problem in JS is simply that:
{ x: 2 }
is THE SAME as:
{ "x": 2 }
(even if you have x a variable defined!)
Solution
Add square brackets [] around the identifier of the key:
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
(Nowadays the keyword var is not much used, so please use instead const or let)
tldr;

Is it necessary to create nested jSON objects before using it?

I think I've seen how to create a JSON object without first preparing it. This is how i prepare it:
obj = {
0:{
type:{}
},
1:{},
2:{}
};
Now I think I can insert a value like: obj.0.type = "type0"; But I'd like to create it while using it: obj['0']['type'] = "Type0";.
Is it possible, or do I need to prepare it? I'd like to create it "on the fly"!
EDIT
I'd like to create JS object "On the fly".
var obj = {};
obj.test = "test"; //One "layer" works fine.
obj.test.test = "test" //Two "layers" do not work... why?
obj = {
0:{
type:{}
},
1:{},
2:{}
};
Now i think i can insert value like: obj.0.type = "type0";
I guess you mean "assign" a value, not "insert". Anyway, no, you can't, at least not this way, because obj.0 is invalid syntax.
But I'd like to create it while using it: obj['0']['type'] = "Type0";
That's fine. But you need to understand you are overwriting the existing value of obj[0][type], which is an empty object ({}), with the string Type0. To put it another way, there is no requirement to provide an initialized value for a property such as type in order to assign to it. So the following would have worked equally well:
obj = {
0:{},
1:{},
2:{}
};
Now let's consider your second case:
var obj = {};
obj.test = "test"; //One "layer" works fine.
obj.test.test = "test" //Two "layers" do not work... why?
Think closely about what is happening. You are creating an empty obj. You can assign to any property on that object, without initializing that property. That is why the assignment to obj.test works. Then in your second assignment, you are attempting to set the test property of obj.test, which you just set to the string "test". Actually, this will work--because strings are objects that you can set properties on. But that's probably not what you want to do. You probably mean to say the previous, string value of obj.test is to be replaced by an object with its own property "test". To do that, you could either say
obj.test = { test: "test" };
Or
obj.test = {};
obj.test.test = "test";
You are creating a plain object in JavaScript and you need to define any internal attribute before using it.
So if you want to set to "Type0" an attribute type, inside an attribute 0 of an object obj, you cannot simply:
obj['0']['type'] = "Type0";
You get a "reference error". You need to initialize the object before using it:
var obj = {
0: {
type: ""
}
};
obj['0']['type'] = "Type0";
console.log(obj['0']['type']);
You could create your own function that takes key as string and value and creates and returns nested object. I used . as separator for object keys.
function create(key, value) {
var obj = {};
var ar = key.split('.');
ar.reduce(function(a, b, i) {
return (i != (ar.length - 1)) ? a[b] = {} : a[b] = value
}, obj)
return obj;
}
console.log(create('0.type', 'type0'))
console.log(create('lorem.ipsum.123', 'someValue'))
Is it necessary to create nested objects before using it?
Yes it is, at least the parent object must exist.
Example:
var object = {};
// need to assign object[0]['prop'] = 42;
create the first property with default
object[0] = object[0] || {};
then assign value
object[0]['prop'] = 42;
var object = {};
object[0] = object[0] || {};
object[0]['prop'] = 42;
console.log(object);
Create object with property names as array
function setValue(object, keys, value) {
var last = keys.pop();
keys.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var object = {};
setValue(object, [0, 'prop'], 42);
console.log(object);

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;
}

Remove \r from a javascript property and value

After I do a csv-upload and parse it I get this kind of object:
var obj = {
"section": "KM1+000",
"velocity\r": "100\r"
}
console.log(obj.section); //KM1+000
console.log(obj.velocity); //undefined
http://jsfiddle.net/zxrk9qx4/
For some reason a \r is added to the last property. This result in I cant access it properly. Is there anyway I can remove \r from my object?
You can access it using obj['velocity\r']
If you want to strip any \rs from all the keys, you can do this.
var old = {
"section": "KM1+000",
"velocity\r": "100\r"
};
function stripCRFromKeys(obj) {
var newObj = {};
for (var key in obj) {
newObj[key.replace(/\r/g, '')] = obj[key];
}
return newObj;
}
console.log(old["velocity\r"]);
var obj = stripCRFromKeys(old);
console.log(obj.velocity)
Notice that you should really try to fix whoever is generating that object if you can

Categories

Resources