How to change the way to access property in an object? - javascript

The task is to change the way to access a property on an object and change the dot operator to a function that will have two arguments: an object and a property.
var exObject = {
arr: [],
obj: {},
str: 'string',
num: 22,
boolean: false,
undeFined: undefined,
nullValue: null
}
for example: typeof change(exObject, "str") should result in string;
function change(obj,property){
var prop="";
for (var key in obj){
if ([key]==property){
prop=obj[key].constructor;
}
}
return prop;
}
My code is clearly wrong - would be happy about any suggestions!

If I understand maybe this will work for you
function chang(obj, property){
if(obj.hasOwnProperty(property)){
return obj[property];
}
return null;
}
PS: the property needs to be a string, such as 'arr'

Related

Javascript: updating an object's property

I'm creating a function and stuck on this prompt:
updateObject() : Should take an object, a key and a value. Should update the property key on object with new value. If does not exist on create it.
This is my code:
function updateObject(object, key, value) {
if (object.key) {
return object.key = value;
} else if (object.key === false) {
return object.key;
}
}
This is the test it's trying to pass:
QUnit.test("updateObject() : Should take an object, a key and a value. Should update the property <key> on <object> with new <value>. If <key> does not exist on <object> create it.", function(assert){
var data = {a: "one", b: "two", "hokey": false};
assert.deepEqual(updateObject(data, "b", "three"), {a:"one", b:"three", hokey: false});
var data = {a: "one", b: "two", "hokey": false};
assert.deepEqual(updateObject(data, "ponies", "yes"), {a:"one", b:"two", hokey: false, ponies: "yes"});
var data = {a: "one", b: "two", "hokey": false};
assert.deepEqual(updateObject(data, "a", Infinity), {a:Infinity, b:"two", hokey: false});
});
What am I doing wrong?
Use square bracket if there is a need to access object key using a variable.Also hasOwnProperty can be used to check if object has a key
function updateObject(object, key, value) {
if (object.hasOwnProperty(key)) {
return object[key] // will return value of the key in that object
} else {
return object[key]=value; // will create a new key and will assign value
}
}
You need to return the updated object from the function for the tests to pass.
function updateObject(object, key, value) {
object[key] = value;
return object;
}

Check if an object is empty and with undefined properties

I'm trying to check the below,
USECASE: 1
var obj = {};
_.isEmpty(obj); ====> returns true
USECASE: 2
var obj = { model: undefined, vendor: undefined, type: undefined }
_.isEmpty(obj); ====> returns false
In usecase 2 is there any other function that i could leverage to return true since all the properties are undefined.
I referred this http://www.ericfeminella.com/blog/2012/08/18/determining-if-an-object-is-empty-with-underscore-lo-dash/ but not sure how to implement it without modifying the native method.
Without Underscore:
const objEmpty = obj => Object.keys(obj).every(key => obj[key] === undefined);
Will accept an object and return true if the object is empty (no properties) or if all the properties have undefined value. Else returns false.
You could use every and pass in the isUndefined predicate:
var obj = { model: undefined, vendor: undefined, type: undefined }
var result = _.every(obj, _.isUndefined);
Alternatively you could omit the undefined values and check whether the object is empty:
var result = _.isEmpty(_.omit(obj, _.isUndefined));

Convert objects present in an object to NULL value

I have the following object names $scope.parameters. When i execute console.log as shown below, i get this result
console.log($scope.parameters);
Result
Object { Name: "Diana", id: 234, Size: Object, Location: Object, Details: "none" }
Name: "Diana"
id: 234,
Size: Object
Location: Object
Details: "none"
As the result shows the elements Size and Location as Object, i want it to be replaced with null. Also, i want it to be dynamic. for e.g. if any of the above elements are Object, it should replace it to null automatically.
Can someone please let me know how to achieve this.
Test out each key of the object with its type if object make them null
if (Object.getPrototypeOf($scope.parameters.Size) === Object.prototype) {
// True if its object change it to null
$scope.parameters.Size = null;
} else {
// do nothing
}
Make a function which takes parameters to test it out and return.
angular.forEach($scope.parameters, function(value, key) {
if(typeof value === "object"){
console.log(key);
$scope.parameters[key] = null;
}
});

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

How can I clone an object and set every properties value to null?

As per title, I need to clone an object in Javascript like that below and set each values to zero. Of course the object properties can change.
{ _id: { action: null, date: null },
avg: null,
min: null,
max: null,
total: null }
// helper method to get the correct object type
function toType(x) {
return ({}).toString.call(x).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
// recursive function that sets all properties to null
// except objects which it passes back into the reset function
function reset(obj) {
// clone the object
var out = JSON.parse(JSON.stringify(obj));
for (var p in out) {
if (toType(out[p]) === 'object') {
reset(out[p]);
} else {
out[p] = null;
}
}
return out;
}
reset(obj);
DEMO

Categories