How can I call an object property with a variable? - javascript

I am trying to solve an issue of calling an object property + function with string.
For example:
var myobject = {
firstName: "Bob",
lastName: "Joe"
};
var show = "lastName";
myobject[show].thisfunction();
In the console everything works as I would expect, but in code it says
Uncaught SyntaxError: Unexpected token [
Any thoughts? Thanks!

This is how it will be done
Here if How you can call the Function on it.
if you want to call the function from current class instance then just replace obj with this.
var proprt = 'firstName'
var myobject = {
firstName: "Bob",
lastName: "Joe"
};
var a =() => { alert('Hello') }
var obj = { Bob:{ thisFn: a } }
obj[myobject[proprt]].thisFn()

Related

Trying to make a data module

I'm trying to make a data module in JavaScript, but can't access the data from outside, while everything works fine when I try to log it from inside
'use strict;'
function manager() {
let data = {};
function define(name, surname, age) {
let length = Object.keys(data).length;
data[`user${length + 1}`] = {
name: name,
surname: surname,
age: age
};
}
function get(num) {
return data[`user${num}`];
}
return {
define: define,
get: get
};
};
manager().define('John', 'Smith', 17);
console.log(manager().get(1));
//undefined
Every time you call manager you define a new variable named data and assign it the value {}.
So manager().define('John', 'Smith', 17); creates an object, assigns some data to it, then the object drops out of scope and is garbage collected.
Then console.log(manager().get(1)); creates a new object, and it has no data in it.
Define the variable and assign the object to it outside the function.
Kindly use module pattern and the execution will like this
var manager = (function() {
'use strict';
let data = {};
function define(name, surname, age) {
let length = Object.keys(data).length;
data[`user${length + 1}`] = {
name: name,
surname: surname,
age: age
};
}
function get(num) {
return data[`user${num}`];
}
return {
define: define,
get: get
};
}());
manager.define('John', 'Smith', 17)
console.log(manager.get(1))
var manager = (function() {
'use strict';
let data = {};
function define(name, surname, age) {
let length = Object.keys(data).length;
data[`user${length + 1}`] = {
name: name,
surname: surname,
age: age
};
}
function get(num) {
return data[`user${num}`];
}
return {
define: define,
get: get
};
}());
manager.define('John', 'Smith', 17)
console.log(manager.get(1))

can you get var name from object with nested objects with lodash?

https://jsfiddle.net/adamchenwei/Lyg2jy61/7/
RESOLVED VERSION:
https://jsfiddle.net/adamchenwei/Lyg2jy61/10/
For some reason findKey for parent top level got undefined
My objective is to get the result = 'myName' with lodash;
var obj = {
myName: {
Adam: 'Man',
},
herName: {
Eve: 'Woman',
},
};
var result = _.findKey(obj, '0'); //as you can see somehow its undefined!
var result2 = _.findKey(obj.myName, '0');
console.log(result);//objective is to get the result = 'myName' with lodash;
console.log(result2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
It looks like what you're actually trying to do is get the first key of an object. To get the keys of an object, you can use _.keys. Then just retrieve the first one.
var obj = {
myName: {
Adam: 'Man',
},
herName: {
Eve: 'Woman',
},
};
console.log(_.keys(obj)[0]);
// Or if you want to do it exclusively with lodash functions
console.log(_.first(_.keys(obj)));
// or
console.log(_.head(_.keys(obj)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
It's not clear what you're after exactly, but using _.findKey on the object you have posted would work like this:
https://jsfiddle.net/Lyg2jy61/8/
var obj = {
myName: {
Adam: 'Man',
},
herName: {
Eve: 'Woman',
}
};
console.log(_.findKey(obj, function(o) { return !!o.Adam; }));
If you just want the first key: _.keys(obj)[0]

Concise way to declare and load object

I have an object that I am creating and a function on that object to load data into the various properties. While the method works as desired, I feel like it might be redundant. Can this be accomplished in a more concise or better way?
var user = {
productLine: {
userActiveValue: []
},
id: {
PACT: null,
EDIPI: null,
AKO: null,
},
name: {
first: null,
last: null,
},
DMIS: null,
region: null,
email: null,
load: true,
loadUser: function (userInfoAPIResponse) {
this.id.PACT = userInfoAPIResponse.UID;
this.id.EDIPI = userInfoAPIResponse.EDIPN;
this.id.AKO = userInfoAPIResponse.akoUserID;
this.name.first = userInfoAPIResponse.fName;
this.name.last = userInfoAPIResponse.lName;
this.DMIS = userInfoAPIResponse.dmisID;
this.region = userInfoAPIResponse.RHCName;
this.email = userInfoAPIResponse.userEmail;
console.log(this);
}
};
function User(userInfoAPIResponse) {
this.id = {
PACT: userInfoAPIResponse.UID,
EDIPI: userInfoAPIResponse.EDIPN,
AKO: userInfoAPIResponse.akoUserID
};
this.productLine = {
userActiveValue: []
};
this.name = {
first: userInfoAPIResponse.fName,
last: userInfoAPIResponse.lName
};
this.DMIS = userInfoAPIResponse.dmisID;
this.region = userInfoAPIResponse.RHCName;
this.email = userInfoAPIResponse.userEmail;
}
var user = new User(...);
Aside from using e.g. user.name = {first: response.fName, last: response.lName} and so on, no. You need to map the variables from one object to another yourself, or just use the response as your user variable.
Alternatively you could just declare user as global (or outer) scope and both declare and set the sub-objects in your callback function. This would mean you potentially had to check for them and their parents being undefined before using them elsewhere, as opposed to a simple not null check.

Accessing Complex Javascript object dynamically [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
I have a javascript object, something like this :
var obj = { simpleName: "some name" name: { firstName: "anudeep", lastName : "rentala" }, address: { country: "XZ", state:"DF" } }
I also have another object like this :
var foo = { loc = "name.firstName" }
Depending on the foo.loc value, I'd have to access the value in obj object.
In this scenario, I'd need to access obj.name.firstname.
So, far, I've tried something like this:
var props = foo.loc.split(".");
for(var prop in props)
{
if (obj.hasOwnProperty(prop))
{
alert(obj[prop])
}
}
My problem is, I can now access only the name property of obj object, how do I step into it, like name.firstName, I'm aware that obj[name][firstName] would work, but how do i do this dynamically ? Like extend this to obj["prop1"]["prop2"]["prop3"] . .. .["propn"]
There are few missing ,, and firstname vs firstName, but if you fix those, then this works great:
var obj = { simpleName: "some name", name: { firstName: "anudeep", lastName : "rentala" }, address: { country: "XZ", state:"DF" } }
var foo = { loc: "name.firstName" }
var props = foo.loc.split(".");
var output = props.reduce( function(prev,prop) {
if (prev.hasOwnProperty(prop)) {
return prev[prop]
} else {
// however you want to handle the error ...
}
}, obj);
alert(output);
You could fix your code like this:
var props = foo.loc.split(".");
var current = obj;
for(var prop in props)
{
if (current.hasOwnProperty(prop))
{
current = current[prop];
alert(current )
}
}
but that probably won't be very useful once you start having more complex "selectors", for example, using arrays ("names[2].firstname").
Here is a function:
var obj = { simpleName: "some name", name: { firstName: "anudeep", lastName : "rentala" }, address: { country: "XZ", state:"DF" } };
var foo = { loc: "name.firstName" };
var checkObj = function(obj, props) {
var temp = obj;
for(var i = 0, len = props.length; i < len; i++) {
if(temp.hasOwnProperty(props[i])) {
temp = temp[props[i]];
}
else return false;
}
return temp;
};
console.log(checkObj(obj, foo.loc.split('.')));

Add JSON objects to JSON object

I have a JSON object employees which I would like to populate with the data in my localstorage. I first saved my JSON object to local storage using stringify() .
sessionStorage.setItem('Employee3', JSON.stringify({id: 3, firstName: 'Dwight', lastName: 'Schrute', title: 'Assistant Regional Manager', managerId: 2, managerName: 'Michael Scott', city: 'Scranton, PA', officePhone: '570-444-4444', cellPhone: '570-333-3333', email: 'dwight#dundermifflin.com', reportCount: 0}));
Now I want to populate my employees object:
employees: {},
populate: function() {
var i = i;
Object.keys(sessionStorage).forEach(function(key){
if (/^Employee/.test(key)) {
this.employees[i] = $.parseJSON(sessionStorage.getItem(key));
i++;
}
});
},
The function $.parseJSON(sessionStorage.getItem(key)) returns the JSON object correctly. Assigning it to the employees object fails:
Uncaught TypeError: Cannot set property 'undefined' of undefined
Array.forEach doesn't preserve this, so you'll have to preserve it yourself. Either of these will work (see mdn):
Object.keys(sessionStorage).forEach(function(key){
if (/^Employee/.test(key)) {
this.employees[i] = $.parseJSON(sessionStorage.getItem(key));
i++;
}
}, this);
var self = this;
Object.keys(sessionStorage).forEach(function(key){
if (/^Employee/.test(key)) {
self.employees[i] = $.parseJSON(sessionStorage.getItem(key));
i++;
}
});
Also, consider using the browser's JSON.parse() instead of jQuery's. Any browser that supports Array.forEach will support JSON.parse().
Yet another way:
Object.keys(sessionStorage).forEach((function(key){
if (/^Employee/.test(key)) {
this.employees[i] = $.parseJSON(sessionStorage.getItem(key));
i++;
}
}).bind(this));
Calling .bind(this) on a function will return a new function bound to the value for this (in the current scope).
the advantage to this is that you don't need to remember which methods support the second "value for this" parameter. It always works. For example, this also works for when adding event listeners to DOM nodes.
tjameson's first suggestion is probably to be preferred in this specific case.
You have a problem with the scope of this. When you are inside the foreach-callback this is not referring to the correct instance.
You need to save a reference to this before and then access the object through that reference (self in the following example):
function something(){
var self = this;
** snip **
employees: {},
populate: function() {
var i = i;
Object.keys(sessionStorage).forEach(function(key){
if (/^Employee/.test(key)) {
self.employees[i] = $.parseJSON(sessionStorage.getItem(key));
i++;
}
});
},
** snip **
}
You have a problem with the value of this inside the forEach callback. Also, And you don't need jQuery to parse JSON.
You can do this instead:
employees: {},
populate: function() {
var that = this;
var i = i;
Object.keys(sessionStorage).forEach(function(key){
if (/^Employee/.test(key)) {
that.employees[i] = JSON.parse(sessionStorage.getItem(key));
i++;
}
});
},
There is no reason to parse JSON, two simple functions will do the job (hope that was the idea):
var employees = {};
function setEmployee( data ) {
var id = data.id;
sessionStorage.setItem('Employee' + id, JSON.stringify( data ));
};
function getEmployee( id ) {
employees[id] = sessionStorage.getItem('Employee' + id);
};
var oneEmployee = {
id: 3,
firstName: 'Dwight',
lastName: 'Schrute',
title: 'Assistant Regional Manager',
managerId: 2,
managerName: 'Michael Scott',
city: 'Scranton, PA',
officePhone: '570-444-4444',
cellPhone: '570-333-3333',
email: 'dwight#dundermifflin.com',
reportCount: 0
};
setEmployee( oneEmployee );
getEmployee( 3 );

Categories

Resources