var config = {
a: 'test',
b: {
c: // SOmeway to access config a value
}
}
IS there any way to access value from class b?
Neither of those things is a class. They're objects.
No, there's no way to access config.a where you have c: in your code, all within the same object literal. You can do it after the fact:
var config = {
a: 'test',
b: {
}
};
config.b.c = config.a;
Note that config.b.c will receive the value of config.a. If someone updates config.a later, config.b.c will not be updated.
If c were a function, you could access config.a from within it:
var config = {
a: 'test',
b: {
c: function() {
// You can use `config.a` here
}
}
};
There, each time you call c, you'll be using the current value of config.a.
Try this i found it in search in for javascript
this.base or this.base()
Related
This question already has an answer here:
object destructuring: how to use intermediate nested property
(1 answer)
Closed 12 days ago.
if I have the following object:
const obj = {
a: {
b: 'val',
},
};
and I want to destructure both a and b from the object, how would I go about doing it? I know this:
const { a: { b } } = obj;
but this doesn't let me access a. How can I also make a accessible in the code?
Just include it.
const obj = {
a: {
b: 'val',
},
};
const { a, a: { b } } = obj;
console.log(a);
console.log(b);
I have a javascript object something like below:
something = {
a: 1,
b: 2,
c: 3,
}
In my “if” condition, I want to return the above object but in my “else” condition, I want to return the same object but without the third property.
c: 3
Is there a way I can do that without repeating or writing the object again in the else condition and excluding the third property (c:3)
Hope I made the question clear. The reason I am doing this is because my if condition is very big and I don't want to write it again in the else block since it will be repeating the entire if logic but with one less property. Please let me know If I was unable to explain my problem
Make the base object without c, then add the c property in the if:
const base = {
a: 1,
b: 2,
};
if (cond) {
return { ...base, c: 3 };
} else {
return base;
}
Another option, by using && to conditionally spread in the c property:
return {
a: 1,
b: 2,
...(cond && { c: 3 })
};
You can use delete operator also as an alternative.
const something = {
a: 1,
b: 2,
c: 3,
};
if (condition) {
return something;
} else {
delete something.c;
return something;
}
var origin = { a: 1, b: { c: 2, d: 3 } }; // origin object
var copy_obj = { ...origin } // or Object.assign({}, origin.b)
delete copy_obj.b.c; // delete copy object
console.log(origin) // { a: 1, b: { d: 3 } };
I'm studying the invariant nature of things.
However, the above example shows that you want to delete the b.c. element of copy_obj. But the origin is also deleted.
Why is this happening?
Object.assign({}, origin.b) or spread syntax {...obj} performs a shallow copy. So the object stored in property b of origin is not cloned i.e it maintains a reference to the object being nested.
Use the following to make a deep clone.
JSON.parse(JSON.stringify(obj))
var origin = { a: 1, b: { c: 2, d: 3 } }; // origin object
var copy_obj = JSON.parse(JSON.stringify(origin));
delete copy_obj.b.c;
console.log(origin)
Note: This only works for objects that can be serialized
For example:
// Object having functions
const obj= {
a: 1,
b: () => {return 2}
}
const copy = JSON.parse(JSON.stringify(obj));
// property `b` won't be copied as it is a function and can't be serialized.
console.log(copy)
Is it possible to use a destructuring assignment inside an object?
This works
const test = {a: 'hey', b: 'hello'}
const {a,b} = test;
const destruct = {
a,
b
};
Would like to do this
const test = {a: 'hey', b: 'hello'}
// something like this
const destruct = {
{a,b}: test
};
const destruct = {
{a}: test,
{b}: test
};
If I understand correctly, it seems the spread syntax is a good fit for what you need.
The spread syntax "..." allows you to "spread" the key/value pairs from a source object (ie test) to a target object (ie destruct):
const test = {
a: 'hey',
b: 'hello',
c: 'goodbye'
}
const destruct = {
// {a,b}: test <-- invalid syntax
...test // equivalent using the "spread" syntax
};
console.log(destruct)
Additionally, if you wanted to select a subset of keys from a source object and spread those into a target object then this can be achieved by the following:
const test = {
a: 'hey',
b: 'hello',
c: 'goodbye'
}
/* Spread subset of keys from source object to target object */
const welcomeOnly = {
...({ a, b } = test, { a, b })
}
console.log('exclude goodbye, show welcomes only:', welcomeOnly);
The second example works by destructing the source object (ie test) into an object, with the subset of keys that we want (a and b).
In the scope of that expression (ie everything between the ( and )), these keys are accessible as local variables. We take advantage of this, and pass those to a new object (ie { a, b }). Because the new object is declared after the ,, it is returned as the result of the expression.
If you are trying to take a subset of properties you can use the rest operator
const test = {
a: 'hey',
b: 'hello',
c: 'goodbye'
};
const { c, ...destruct } = test;
console.log(destruct);
This assigns c to a const and the the left over properties are assigned to the const destruct. List all the unwanted properties first and then the left over properties are caught with the rest operator.
Works with arrays as well.
const test = ['hey', 'hello', 'goodbye'];
const [ first, ...rest ] = test;
console.log(rest);
You can try to work like this for destructuring arrays!
let abc = {
a: 'hello',
b: 'hey',
c: 'hi, there!'
}
let {a: x, b:y, c:z} = abc;
console.log(x,y,z)
// "hello"
"hey"
"hi, there!"
I have an ObjectManager, which holds a reference to all objects that are created. The problem is that the ObjectManager is not referencing the object that was created, but instead it seems to be creating a new instance of it. Any help would be appreciated. Thanks!
var Fieldset = function (options) {
var fieldset = ($.extend(true, {
id: '',//Let's assume this has been overridden with 'MyFieldset' via the options param.
title: '',
accordion: '',
fields: [],
hidden: false,
Show: function () { $('#' + this.id).show() },
Hide: function () { $('#' + this.id).hide() }
}, options));
if (fieldset.id != null && fieldset.id != '')
ObjectManager.fieldsets[fieldset.id] = fieldset;//Save a reference to this object in the ObjectManager, so I can call ObjectManager.GetFieldset('MyFieldset'). A reference is only saved if an id is provided.
log(ObjectManager.GetFieldset(fieldset.id) == fieldset);//true
return fieldset;
}
Edit:
Sorry, I thought it was clear what I wanted this to do. There is nothing special about ObjectManger. It just has a property and Get method for each of my objects. For simplicity I only included the fieldsets property and Getter. I hope this clears up my intentions.
var ObjectManager =
{
fieldsets: {},
GetFieldset: function (id) { return this.fieldsets[id]; }
};
Edit2:
After some testing, I found something odd... Hopefully someone can explain to me why this is happening.
var myFieldset = new Fieldset({ id: 'MyFieldset' });
log(myFieldset == ObjectManager.GetFieldset('MyFieldset'));//I just found that it is true in this case...
//... However, this is not the normal way I create Fieldsets... This is:
var editForm = new Form({
dataStore: function () { return ClientsDS; },
id: 'ClientEditForm',
fieldSets: [
new Fieldset({
id: 'ClientDetailsFieldSet',
title: 'Details',
fields: [
new Field({ id: 'ClientID', name: 'ID', property: 'ID', fieldType: 'hidden', value: '0' })
]
})
]
});
log(editForm.fieldSets[0] == ObjectManager.GetFieldset('ClientDetailsFieldSet'));//false
On EDIT2:
Your objects are not equal, because they are not the same. The equality operator does not say these two objects have the same key/value pairs, they are equal when they are the same object.
For instance,
var a = b = {a: 1, b:2};
//This is b = {a: 1, b: 2}; a = b; In case you were wondering
a === b //true
var a = {a: 1, b: 2},
b = {a: 1, b: 2};
a === b //false
Hmm, your Fieldset constructor is returning an object. Perhaps try calling it as Fieldset({...}) instead of new Fieldset({...})?
I am assuming that your Form class looks something like your Fieldset class, i.e. that it $.extends (makes a deep copy) the options you give it with its internal "prototype". The object returned is the extended prototype not the options extended with the prototype object. Try changing the order of your $.extend arguments (put options second and the internal "prototype" third) and see if that changes anything. Alternatively, post your Form class :-)