var config = {
xxx : 'foo'
}
var env = {
foo : {
},
bar : {
}
}
How can I use an objects value to retrieve values from another object?
like:
env.config.xxx?
var object1 = { value : 'hello' }
var object2 = { o : object1 }
alert(object2.o.value);
Related
let's say I have a nested object like this:
let object = {
another : {
yet_another : {
last_one : {
some_property : [1,2,3]
}
}
}
}
I can access some_property like this:
object.another.yet_another.last_one.some_property;
And let's say I'm referring to this object in a variable:
var x = object.another.yet_another.last_one.some_property;
How can I tell what's the parent object of some_property if I only have access the x variable? is it even possible in JavaScript?
No, it's not possible. An object doesn't have a "parent" per se. Observe:
let object = {
another : {
yet_another : {
last_one : {
some_property : [1,2,3]
}
}
}
};
let another_object = {
foo: object.another.yet_another.last_one.some_property
};
Now what? The array is now equally a member of both objects.
No, because when doing the following line;
var x = object.another.yet_another.last_one.some_property;
then you assign x to the value of some_property, nothing more.
Based on your comment to an answer, the solution to your (actual) problem should be don't move objects around. Mutability can be very very expensive (eventually prohibitively) when it comes to maintaining an application.
Just create new objects:
const firstObject = {
prop1: 'some value',
prop2: {
prop3: 'some value',
prop4: [1,2,3,4]
}
}
// don't do
const secondObject = { }
secondObject.prop2.prop4 = firstObject.prop2.prop4
// instead do
const secondObject = { ... }
const newObject = {
...secondObject,
prop2: {
...secondObject.prop2,
prop4: firstObject.prop2.prop4
}
}
You may want to look into immutablejs.
Why am I unable to read the following variables in a nested map?
for (const key in doc.data().category) {
const location = doc.data().location; // declared but it's value is never read"
const mainCategory = doc.data().category; // declared but it's value is never read"
const subCategory = doc.data().category[key]; // declared but it's value is never read"
categoryCount.doc('categoryCount')
.set({ location: { mainCategory: { subCategory: "test" } } },
{ merge: true })
.catch((error) => console.log(error));
Console logs to clarify:
console.log(location); // "New York"
const map = { location: { mainCategory: { subCategory: true } } };
console.log(map); // "location": {"mainCategory": {"subCategory": true}}
If you want to use the value of a variable as the name of a property, you have to tell JavaScript that you want to insert that value (as opposed to just naming the key):
{ [location]: { mainCategory: { subCategory: "test" } } }
Notice the square brackets around location.
See also: Square Brackets Javascript Object Key
I think you may be misunderstanding how JavaScript objects work. Imagine you have three variables called:
var A = 'X';
var B = 'Y';
var C = 'Z';
when you code:
{
A: {
B: {
C: "test"
}
}
}
You do not end up with an object of value:
{
X: {
Y: {
Z: "test"
}
}
}
If that is what you want, consider:
var O1 = {};
O1[C] = "test";
var O2 = {};
O2[B] = O1;
var O3 = {};
O3[A] = O2;
// O3 is the top level object
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('.')));
I have several Ajax-requests that retrieves data from the server...
I want to add them together, so I can use the data set later.
This is how one JSON-looks like:
{
"51" : { id:"51", name:"frank" },
"52" : { id:"52", name:"jonny" }
}
A second later there might come another one, with the exactly the same structure. How do I just "append" a new json into this to make a large object with the same structure..
EG: (append like this)
{
"51" : { id:"51", name:"frank" },
"52" : { id:"52", name:"jonny" },
"72" : { id:"72", name:"daniel"},
"73" : { id:"73", name:"lisa"},
"74" : { id:"74", name:"ida"},
"75" : { id:"75", name:"ali"}
}
Assuming that the ID will always be unique, you can do something like:
var buffer = {};
messageSource.on('message', function (msg) {
var msgKeys = Object.keys(msg); // Get the list of IDs
msgKeys.forEach(function (key) { // For each numeric key...
buffer[key] = msg[key]; // Copy the message
});
});
If you cannot guarantee unique IDs, you'll need some minor changes:
var buffer = {};
messageSource.on('message', function (msg) {
var msgKeys = Object.keys(msg);
msgKeys.forEach(function (key) {
buffer[key] = (buffer[key] || []).push(msg[key]); // Only change, append to list for that key
});
});
You should use Jquery $.merge:
var obj1 = {
"51" : { id:"51", name:"frank" },
"52" : { id:"52", name:"jonny" }
};
var obj2 = {
"72" : { id:"72", name:"daniel"},
"73" : { id:"73", name:"lisa"},
"74" : { id:"74", name:"ida"},
"75" : { id:"75", name:"ali"}
}
var result = $.extend(obj1, obj2);
Working exemple here
I am using a Module Pattern in a javascript code, initially i have to make a private property equal to another, but it looks like it's just a symlink, like in the example.
I need two independant private properties but sometimes sync them.
Thanks for help.
Maxime.
var module = (function () {
var data1 = {
pro1 : "aaa",
pro2 : "bbb"
};
var data2 = {};
function init() {
data2 = data1;
}
function logg() {
console.log(data1);
console.log(data2);
}
function test() {
data2.pro1 = 'haha';
}
return {
init : init,
logg : logg,
test : test
}
}());
module.init();
module.logg();
// data1 = { pro1 : "aaa", pro2 : "bbb" }
// data2 = { pro1 : "aaa", pro2 : "bbb" }
module.test();
module.logg();
// data1 = { pro1 : "haha", pro2 : "bbb" }
// data2 = { pro1 : "haha", pro2 : "bbb" }
If your simple object example is similar to the structure you're going to be using, aka no prototypical inheritances from your objects, you could loop through your object and assign values from your old to new. Otherwise your simple assignment will just be pass by reference.
ie:
for(var i in data1){
data2[i] = data1[i];
}