Setting object literal value dynamically - javascript

I know you can not set a key value dynamically, but what about the value?
I'm asking b.c. I need to know the best way to initialize an object. Here is how I do it currently:
var object_pipe = {
model : 'MUserAny',
page : {
email: '0'
},
args : {
foo : '0'
}
};
object_pipe.args.foo = localStorage.foo; // Statement A
I'd like to put statement A directly in the object literal but am not sure if it is possible or the correct syntax.
Aslo, Do I need to explicitly declare properties when I can not set them in the object literal as in here...does page need to be there?
var object_pipe = {
model : 'MUserNew',
page : {
}
};
for( var key in form_elements ) {
object_pipe.page[ form_elements[key].name ] = form_elements[key].value ;
}

You don't need to explicitly declare variables but you can just initialize the key with an empty "whatever", can be an array, string, object literal etc. You can add properties later.
var o = {
a: [],
b: {}
}
o.a[0] = 'foo'
o.b.c = 'baz'
o.d = 'pom' // New

What's wrong with this:
var object_pipe = {
model : 'MUserAny',
page : {
email: '0'
},
args : {
foo : localStorage.foo
}
};
DEMO

Related

checking inline value is exists, set to object property in declaring object _ JavaScript

suppose we want to create a new object.
let myObject = {};
and we have some property that exists in another object like :
let b = { foo: "bar"};
is it possible to check if b?.foo append foo to myObject inline in the declaration of the object?
something like this :
let myObject = { b?.foo }
I think the best you can do is :
let myObject = {
some: "prop",
...(b?.foo && {foo:b.foo})
}
Or if you want to pass all the object
let myObject = {
some: "prop",
...(b?.foo && b)
}

How to refer to class using variable

If I have this object:
var myclass = {
foo: {
bar: function(var) {}
},
some: {
bar: function(var) {}
}
}
and I want to call the bar function depending on a variable that defines the parent level of the object like this:
var part = "some";
myclass.part.bar(var);
How can I do?
You can do it using array access notation:
myclass[part].bar(var);
JavaScript objects are like associative arrays, and you can use a property name to either set or get the property's value, you can even create new properties with this syntax.
For example:
var obj = { a : 1 };
console.log(obj["a"]); // 1
obj["b"] = 2; // this creates a property called b and assigns 2 as the value
console.log(obj["b"]); // 2
You can keep a reference to a function as a variable, which is a little cleaner than a string.
var func = myclass.foo.bar;//or myclass.some.bar
...
func.call(myclass, var);
Or keep a reference to the part:
var part = myclass.foo;//or myclass.some
part.bar.call(myclass, var);

Class members in Backbone/Parse using each other

var User = Parse.User.extend({
// instance members
}, {
// types
TYPE_TRAINER : 1,
TYPE_ATHLETE : 2,
types: {
TYPE_TRAINER : 'Trainer',
TYPE_ATHLETE : 'Athlete'
}
});
I want to have TYPE_TRAINER and TYPE_ATHLETE maintain the values of 1 and 2 as defined prior to the types object so that I can use the types object in a template.
If you don't know about Parse, Parse.User is an extension of Backbone.Model.
Thanks!
What you're asking is not directly possible in JavaScript object literals. Object literals are always a literal value on the left hand / key side.
The closest you could get is to use the TYPE_TRAINER and TYPE_ATHLETE keys as variables to assign values via the square bracket syntax for accessing object key/value pairs:
var a = 1;
var b = 2;
var obj = {};
obj[a] = "a";
obj[b] = "b";
This will result in the obj object looking like this:
{
1: "a",
2: "b"
}
So you could do something like this, to get what you want in your code:
var userMethods = {
// types
TYPE_TRAINER : 1,
TYPE_ATHLETE : 2
};
userMethods[userMethods.TYPE_TRAINER] = 'Trainer';
userMethods[userMethods.TYPE_ATHLETE] = 'Athlete';
var User = Parse.User.extend({
// instance members
}, userMethods);
It's more code than you probably want, but it's the only way to achieve what you want because of the object literal syntax.
The Parse.Object Javascript documentation says:
You should call either:
var MyClass = Parse.Object.extend("MyClass", {
// Instance properties
}, {
// Class properties
});
or, for Backbone compatibility:
var MyClass = Parse.Object.extend({
className: "MyClass",
// Other instance properties
}, {
// Class properties
});
If you are wanting to extend the Parse.User "class" (it's an object, not a class), you need to include the className as described above because Parse.User is itself an extension of Parse.Object.

Javascript Object Literal referring to another property in itself from another property

I have a object literal:
var obj = {
a : document.getElementById("ex1"),
b : obj.a.document.getElementsByTagName("div")
};
I am having trouble with the b property, for some reason it is not letting that happen. Is this possible?
The modern way to do this is with getter methods:
let obj = {
firstName: "A’dab",
lastName: "Farooqi"
get fullName() {
return this.firstName+" "+this.lastName;
},
}
So now you can just write obj.fullName - no need for the parentheses on the end.
You need two steps:
var obj = {
a : document.getElementById("ex1")
};
obj.b = obj.a.document.getElementsByTagName("div")
Or:
var temp = document.getElementById("ex1")
var obj = {
a : temp,
b : temp.document.getElementsByTagName("div")
};
When the property b is being defined, obj is not defined yet. One way to get around that problem is to make your property a function so that it's not evaluated until called.
var obj = {
a : document.getElementById("ex1"),
b : function() {
// This is not evaluated until obj.b() is called
return obj.a.document.getElementsByTagName("div");
}
};
obj.b();
If you really want it to be a property, you have to do it in two steps as Tomasz Nurkiewicz shows

Dynamically Add Variable Name Value Pairs to JSON Object

I have a json object full of ips like
var ips = {}
I then add ip objects to this object like so
ips[ipID] = {}
I then need to add dynamic/variable name value pairs to each ip so I am using code like this
var name; var value; var temp = {};
tmp[name] = value
My question is, how can I add these name value pairs/ tmp to my ipID objects so that my outcome turns out like
ipID = { name : value, anotherName : anotherValue }
That's not JSON. It's just Javascript objects, and has nothing at all to do with JSON.
You can use brackets to set the properties dynamically. Example:
var obj = {};
obj['name'] = value;
obj['anotherName'] = anotherValue;
This gives exactly the same as creating the object with an object literal like this:
var obj = { name : value, anotherName : anotherValue };
If you have already added the object to the ips collection, you use one pair of brackets to access the object in the collection, and another pair to access the propery in the object:
ips[ipId] = {};
ips[ipId]['name'] = value;
ips[ipId]['anotherName'] = anotherValue;
Notice similarity with the code above, but that you are just using ips[ipId] instead of obj.
You can also get a reference to the object back from the collection, and use that to access the object while it remains in the collection:
ips[ipId] = {};
var obj = ips[ipId];
obj['name'] = value;
obj['anotherName'] = anotherValue;
You can use string variables to specify the names of the properties:
var name = 'name';
obj[name] = value;
name = 'anotherName';
obj[name] = anotherValue;
It's value of the variable (the string) that identifies the property, so while you use obj[name] for both properties in the code above, it's the string in the variable at the moment that you access it that determines what property will be accessed.
With ECMAScript 6 there is a better way.
You can use computed property names in object property definitions, for example:
var name1 = 'John';
var value1 = '42';
var name2 = 'Sarah';
var value2 = '35';
var ipID = {
[name1] : value1,
[name2] : value2
}
This is equivalent to the following, where you have variables for the property names.
var ipID = {
John: '42',
Sarah: '35'
}
when using javascript objects, you can also just use "dot notation" to add an item, (which JSLint prefers)
var myArray = { name : "john" };
//will initiate a key-value array with one item "name" and the value "john"
myArray.lastName = "smith";
//will add a key named lastName with the value "smith"
//Object {name: "john", lastName: "smith"}
Here is a screenshot from testing in the Chrome console
I'm assuming each entry in "ips" can have multiple name value pairs - so it's nested. You can achieve this data structure as such:
var ips = {}
function addIpId(ipID, name, value) {
if (!ips[ipID]) ip[ipID] = {};
var entries = ip[ipID];
// you could add a check to ensure the name-value par's not already defined here
var entries[name] = value;
}
in Javascript.
var myObject = { "name" : "john" };
// { "name" : "john" };
myObject.gender = "male";
// { "name" : "john", "gender":"male"};
if my understanding of your initial JSON is correct, either of these solutions might help you loop through all ip ids & assign each one, a new object.
// initial JSON
var ips = {ipId1: {}, ipId2: {}};
// Solution1
Object.keys(ips).forEach(function(key) {
ips[key] = {name: 'value', anotherName: 'another value'};
});
// Solution 2
Object.keys(ips).forEach(function(key) {
Object.assign(ips[key],{name: 'value', anotherName: 'another value'});
});
To confirm:
console.log(JSON.stringify(ips, null, 2));
The above statement spits:
{
"ipId1": {
"name":"value",
"anotherName":"another value"
},
"ipId2": {
"name":"value",
"anotherName":"another value"
}
}
From what the other answers have proposed, I believe this might help:
var object = ips[ipId];
var name = "Joe";
var anothername = "Fred";
var value = "Thingy";
var anothervalue = "Fingy";
object[name] = value;
object[anothername] = anothervalue;
However, this is not tested, just an assumption based on the constant repetition of:
object["string"] = value;
//object = {string: value}
You can achieve this using Lodash _.assign function.
var ipID = {};
_.assign(ipID, {'name': "value"}, {'anotherName': "anotherValue"});
console.log(ipID);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.10/lodash.min.js"></script>

Categories