How to use multiple values in hasOwnProperty [duplicate] - javascript

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 4 years ago.
Say I have this object:
myObj = {
level1: {
level2: {
name: 'Frank'
}
}
};
How can I use hasOwnProperty() to check multiple depths of my object. Something like this works:
if (myObj.hasOwnProperty('level1') {
if (myObj.hasOwnProperty('level2') {
if (myObj.hasOwnProperty('name') {
console.log(myObj.level1.level2.name)
}
}
}
I was hoping for something like:
myObj.hasOwnProperty(['level1', 'level2', 'name']);
myObj.hasOwnProperty('level1.level2.name);
My goal is to not console.log(myObj.level1.level2.name) if not all the properties are there, so you can answer this question by providing an alternate for hasOwnProperty also.

You could take a closure over the object and check the keys.
const check = o => k => [o.hasOwnProperty(k), o = (o || {})[k]][0];
var myObj = { level1: { level2: { name: 'Frank' } } };
console.log(['level1', 'level2', 'name'].every(check(myObj)));
console.log(['level1', 'level3', 'name'].every(check(myObj)));

Related

js destructure and define field [duplicate]

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);

How to select all props but one from object [duplicate]

This question already has answers here:
Destructuring object and ignore one of the results
(4 answers)
Closed 3 years ago.
I wanna to select all props but one from a javascript object but doing in elegant way using ES6, is this possible?
example:
const myObj = { prop1, prop2, prop3 }
const newObj = {
…myObject.remove(prop3)
}
then newObj should be { prop1, prop2}
if destruct I can select some, or all
const newObj = {
…myObject
}
const {prop1, prop2} = myObjct
but I dont know how to select all but one.
You can use the object rest syntax to assign all other properties to newObj, except those explicitly stated:
const myObj = { prop1: 1, prop2: 2, prop3: 3 }
const { prop1, ...newObj } = myObj
console.log(newObj)

referencing outer layer of nested object in javascript in object literal [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 3 years ago.
I'm looking to do something like the task here Self-references in object literals / initializers , except that it would be for the value of an aunt/uncle key, or the sibling key of the parent object. For example:
const obj = {
parent: {
child: {
aunt: /* aunt object */
}
},
aunt: {
foo: {
bar: 1
}
}
}
There's a very similar ask here Reference nested 'sibling'-property in object literal but unfortunately, not quite what I'm looking for. Ideally, the solution would be extensible and probably would need to be to handle cases where I'd want to access a great-grandcousin object related to a key if need be. Thanks!
It's not possible in a single object literal. You'd have to define the object first, then assign to the aunt key .
const obj = {
parent: {
child: {
}
},
aunt: {
foo: {
bar: 1
}
}
};
obj.parent.child.aunt = obj.aunt;
console.log(obj.parent.child.aunt === obj.aunt)
Or, you can define aunt beforehand:
const aunt = {
foo: {
bar: 1
}
};
const obj = {
parent: {
child: {
aunt
}
},
aunt
};
console.log(obj.parent.child.aunt === obj.aunt)

Dynamically access object properties using a variable [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 years ago.
I have a large object with multiple objects nested within it. I have a function that will take the key of one of the objects, and I want to add a new property to the sub-object that is called. Something like https://jsfiddle.net/cf15xdfm/2/
var my_object = {
object1: {
key: 'value',
key2: 'value2'
},
object2: {
key: 'othervalue',
key2: 'another'
}
}
function doSomething(obj_key) {
// add a new property to the object
my_object.obj_key.new_prop = 'this_new_prop';
}
doSomething('object1');
console.dir(my_object);
How do I reference the variable obj_key in the doSomething method so that I can alter the desired object?
Make use of brackets notation for accessing dynamic keys
var my_object = {
object1: {
key: 'value',
key2: 'value2'
},
object2: {
key: 'othervalue',
key2: 'another'
}
}
function doSomething(obj_key) {
// add a new property to the object
my_object[obj_key].new_prop = 'this_new_prop'; // using bracket notation here
}
doSomething('object1');
console.dir(my_object);
You can use:
my_object[obj_key].new_prop='this_new_prop';
You can call properties as string like this:
obj['property_name']
So you should do this:
my_object[obj_key].new_prop = 'this_new_prop';
Edit: Sorry didn't see the answer was already there

How to remove properties from an object array? [duplicate]

This question already has answers here:
Remove property for all objects in array
(18 answers)
Closed 2 years ago.
I am trying to remove a property from an object array.
export class class1 {
prop1: string;
prop2: string;
prop3: string;
}
export class class2 {
myprop = [
{ prop1:'A', prop2:"1", prop3:"descr1" },
{ prop1:'B', prop2:"2", prop3:"descr2" },
{ prop1:'C', prop2:"3", prop3:"descr3" },
];
get(): class1[] {
return this.myprop ;
}
add(value: class1): void {
this.myprop.push(value);
}
}
var var1 = class2.get();
var var2 =
I would like var2 contain something like this.
[
{ prop1:'A', prop3:"descr1" },
{ prop1:'B', prop3:"descr2" },
{ prop1:'C', prop3:"descr3" },
];
Is there a way to convert/cast var1 into the above? In other words, I would like to remove prop2 from var1 object array and assign it to var2. How can I do that?
This seems like a great time to use .map()
var var1 = class2.get();
var var2 = var1.map(obj => ({prop1: obj.prop1, prop3: obj.prop3}));
Short, sweet, and does what you want.
MDN docs for .map()
You can delete object property like this e.g.
var myprop = [
{prop1: 'A', prop2: "1", prop3: "descr1"},
{prop1: 'B', prop2: "2", prop3: "descr2"},
{prop1: 'C', prop2: "3", prop3: "descr3"},
];
myprop = myprop.filter(function (props) {
delete props.prop2;
return true;
});
console.log(myprop);
Casting in TypeScript won't remove the property but only hide it in your IDE because it will be compile to JavaScript for runtime.
First of all, if you don't want to remove prop2 from var1 while deleting the property from var2 you need to clone it. For that you will need this JavaScript function:
function cloneObject(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
var temp = obj.constructor(); // give temp the original obj's constructor
for (var key in obj) {
temp[key] = cloneObject(obj[key]);
}
return temp;
}
Use the clone function to clone var1 and loop each object in var2 to remove property prop2. You can do so with JavaScript by combining array.forEach and delete:
var var2 = cloneObject(var1);
var2.forEach((obj) => { delete obj.prop2; });
Doing so will KEEP prop2 in var1 but REMOVE it from var2
// Use delete:
var user = {
firstname:"Jack",
lastname:"Prince",
};
var result = delete user.firstname;
console.log(result,"firstname deleted");
console.log(user);
//using Object rest spread operator
const { firstname, ...data } = user;
console.log(data);

Categories