Using variables to build JS Object - javascript

I want to create an object that has some keys which come from a variable parameter.
Let's say for example that prod_id below is a variable containing some value... I want to create an object which has an attribute with key of that 'prod_id' and value of 1. However this does not work? Is this possible to achieve? if so, how? thanks a heaps
var cart_obj;
cart_obj = {
prod_id : 1
};
localStorage.setItem("cart", JSON.stringify(cart_obj));

You can't do it with a simple object literal. You can do this however:
var cart_obj = {};
cart_obj[prod_id] = 1;
JavaScript object literal syntax makes no provisions for expressions on the left side of a property declaration stanza.

var cart_obj = {};
cart_obj.prod_id = 1;
or
var cart_obj = {};
cart_obj[prod_id] = 1;

Related

javascript - Reduce huge array list to make it more readable

I have a huge array with list of variables going from 1 to 90 and it's really dirty and makes the js file little redable.
How can I clean it/factorize ? I tried some ways but it did not work. It's important to understand that below, all the i18nrotatingKw11/2... are not strings, they're variables.
const rotatingKwsListArr = [i18nrotatingKw1,i18nrotatingKw2,i18nrotatingKw3,i18nrotatingKw4,i18nrotatingKw5,i18nrotatingKw6,i18nrotatingKw7,i18nrotatingKw8,i18nrotatingKw9,i18nrotatingKw10,i18nrotatingKw11,i18nrotatingKw12,i18nrotatingKw13,i18nrotatingKw14,i18nrotatingKw15,i18nrotatingKw16,i18nrotatingKw17,i18nrotatingKw18,i18nrotatingKw19,i18nrotatingKw20,i18nrotatingKw21,i18nrotatingKw22,i18nrotatingKw23,i18nrotatingKw24,i18nrotatingKw25,i18nrotatingKw26,i18nrotatingKw27,i18nrotatingKw28,i18nrotatingKw29,i18nrotatingKw30,i18nrotatingKw31,i18nrotatingKw32,i18nrotatingKw33,i18nrotatingKw34,i18nrotatingKw35,i18nrotatingKw36,i18nrotatingKw37,i18nrotatingKw38,i18nrotatingKw39,i18nrotatingKw40,i18nrotatingKw41,i18nrotatingKw42,i18nrotatingKw43,i18nrotatingKw44,i18nrotatingKw45,i18nrotatingKw46,i18nrotatingKw47,i18nrotatingKw48,i18nrotatingKw49,i18nrotatingKw50,i18nrotatingKw51,i18nrotatingKw52,i18nrotatingKw53,i18nrotatingKw54,i18nrotatingKw55,i18nrotatingKw56,i18nrotatingKw57,i18nrotatingKw58,i18nrotatingKw59,i18nrotatingKw60,i18nrotatingKw61,i18nrotatingKw62,i18nrotatingKw63,i18nrotatingKw64,i18nrotatingKw65,i18nrotatingKw66,i18nrotatingKw67,i18nrotatingKw68,i18nrotatingKw69,i18nrotatingKw70,i18nrotatingKw71,i18nrotatingKw72,i18nrotatingKw73,i18nrotatingKw74,i18nrotatingKw75,i18nrotatingKw76,i18nrotatingKw77,i18nrotatingKw78,i18nrotatingKw79,i18nrotatingKw80,i18nrotatingKw81,i18nrotatingKw82,i18nrotatingKw83,i18nrotatingKw84,i18nrotatingKw85,i18nrotatingKw86,i18nrotatingKw87,i18nrotatingKw88,i18nrotatingKw89,i18nrotatingKw90];
All the variables declared with var in global scope are present in window object. You can access them using Bracket Notation. Below is example with 3 variables
var i18nrotatingKw1 ="something 1";
var i18nrotatingKw2 = "something 2"
var i18nrotatingKw3 = "something 3"
let arr = Array(3).fill().map((x,i)=>window[`i18nrotatingKw${i+1}`])
console.log(arr);
Assuming you can't simply store the values of i18nrotatingKw1/... in an array to begin with, or declare them as properties of an object, remember that variables declared with var are hoisted to the variable object of the execution context. For example if you have in a JavaScript document:
var test1 = 'first'
var test2 = 'second'
then
console.log(this['test1'])
results in logging 'first'
You can use this to iterate over the number postfix in your variable names.
The workaround solution is using eval()
For instance:
var evalString = 'const rotatingKwsListArr = ['
for (var i = 1; i <= 91; i++) {
evalString += 'i18nrotatingKw' + i + ','
}
evalString = evalString.slice(0, -1) + '];'
eval(evalString)
From MDN: The eval() function evaluates JavaScript code represented as a string.

How to add a value to an Object in javascript?

Let's take an example in javascript
var b = function(){
var key = {};
var result = [];
var a =
[{people: "people1"},
{people: "people2"},
{people: "people2"},
{people: "people3"}]
for(i=0;i<a.length;i++)
{
var val = a[i][people];
if(angular.isUndefined(key[val]))
{
Key[val] = "abc"; /////This line is foreign to my knowledge.
result.push(val);
}
}
return result;
}
Now in this Example i am creating an object Key and a array result.
The for loop will loop through the a variable and store the value of people property in the var val.
The angular.Isundefined function check whether the key[val] contains any duplicate data if not then it will add using the
Key[val] = "abc".
1) Now i have no idea how this line is creating the value and key pair in the key object.
2) Please tell me other ways to add value to the object.
O/P is as follows
key = Object {people1: abc, people2: abc, people3: abc}
hence it is adding value to key object without duplicating the value.
P.S. it is just an example not the real code.
From the link of Andreas in comments
I think this solves my problem.
the other way to add the key and value to the JSON object is like this.
obj = {};
obj[people1] = "data";
obj[people2] = "data";
obj[people3] = "data";
console.log(obj);
The key cannot be same but the value can be same.
So this is what my question was
Key[val] = "abc";
this line is getting the val variable dynamically and adding the val variable as the key and the value is abc.
Twist:
Do you think that
key.val = "abc";
work?
No:
This is what provided by the site
Any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number)
can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).
in the following example i add count in my json my json come from ajax but i want to add count so add count below code that's work fine for me here .count is my custom value added by me, it is not part of my response
$scope.data = response.items;
for (var i = 0; i < response.items.length; i++) {
response.items[i].count = i;
}

Property of property using String in brackets?

Let's say I have a complex object with properties that have properties.
var x = {};
x.A.B = 'Hello';
x.A.C = 'World!';
x.D.E = 100;
x.D.F = 2.5;
Is there anything I could put in a single set of square brackets in order to get back any of these properties? A simple test shows that x['A.B'] does not return 'Hello'. Is there any syntax for doing this?
If you don't want to iterate you could do it fairly safe with eval in strict mode. Not that I recommend doing this. But it's a way to do it.
var x = {A:{}};
x.A.B = 'Hello';
var propertyPath = 'A.B';
var value = eval('"use strict"; x.' + propertyPath);
console.log(value);
Another more reusable way would be to create a new Function object instead of using eval.
function propertyValue(obj, propertyPath) {
'use strict';
return (new Function('obj', 'return obj.' + propertyPath))(obj);
}
var value = propertyValue(x, 'A.B');
It is practically the same but has a clear definition.

How can I store reference to a variable within an array?

I'm trying to create an array that maps strings to variables. It seems that the array stores the current value of the variable instead of storing a reference to the variable.
var name = "foo";
var array = [];
array["reference"] = name;
name = "bar";
// Still returns "foo" when I'd like it to return "bar."
array["reference"];
Is there a way to make the array refer to the variable?
Put an object into the array instead:
var name = {};
name.title = "foo";
var array = [];
array["reference"] = name;
name.title = "bar";
// now returns "bar"
array["reference"].title;
You can't.
JavaScript always pass by value. And everything is an object; var stores the pointer, hence it's pass by pointer's value.
If your name = "bar" is supposed to be inside a function, you'll need to pass in the whole array instead. The function will then need to change it using array["reference"] = "bar".
Btw, [] is an array literal. {} is an object literal.
That array["reference"] works because an Array is also an object, but array is meant to be accessed by 0-based index. You probably want to use {} instead.
And foo["bar"] is equivalent to foo.bar. The longer syntax is more useful if the key can be dynamic, e.g., foo[bar], not at all the same with foo.bar (or if you want to use a minimizer like Google's Closure Compiler).
Try pushing an object to the array instead and altering values within it.
var ar = [];
var obj = {value: 10};
ar[ar.length] = obj;
obj.value = 12;
alert(ar[0].value);
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called myTarget, then use:
myRef = function (newVal) {
if (newVal != undefined) myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(<the value you want to set>);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray[0]() to read and myArray[0](<new value>) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.
My solution to saving a reference is to pass a function instead:
If the variable you want to reference is called 'myTarget', then use:
myRef = function (newVal) {
if (newVal != undefined)
myTarget = newVal;
return myTarget;
}
To read the value, use myRef();. To set the value, use myRef(value_to_set);.
Helpfully, you can also assign this to an array element as well:
var myArray = [myRef];
Then use myArray0 to read and myArray[0](value_to_set) to write.
Disclaimer: I've only tested this with a numerical target as that is my use case.

Use string to access object in Javascript

I have a variable containing a string "Y.Plugin.abcd" and I would like to access an object with the same name...I'm using YUI 3 and attempted the Y.namespace method with no luck.
var nm = "Y.Plugin.abcd";
Y.log(Y.Plugin.abcd); //outputs the correct object
Y.log(Y.namespace(nm)); //outputs an empty object
I'm pretty much looking for any method, YUI or not, to be able to do what is a rather simple task in PHP.
In plain JavaScript, you could probably split your string and then use the subscript notation, as follows:
var nm = "Y.Plugin.abcd";
var nm_array = nm.split('.'); // split the nm string
var obj = window; // set our reference to the global object
for (var i = 0; i < nm_array.length; i++) {
obj = obj[nm_array[i]]; // walk through all the namespaces
}
Y.log(obj); // obj will hold a reference to Y.Plugin.abcd

Categories