How to conditionally remove a property from an object? [duplicate] - javascript

This question already has answers here:
Iterative conditional removal of object property using 'for..in' and 'if' [duplicate]
(2 answers)
Closed 5 years ago.
Write a function called "removeNumbersLargerThan".
Given a number and an object, "removeNumbersLargerThan" removes any properties whose values are numbers greater than the given number.
var obj = {
a: 8,
b: 2,
c: 'montana'
}
removeNumbersLargerThan(5, obj);
console.log(obj); // --> { b: 2, c: 'montana' }
my code:
function removeNumbersLargerThan(num, obj) {
// your code here
if (obj[prop] < num) {
delete obj[prop];
}
}
What's wrong with my code? I'm not sure how to get rid of a property from an object if the property isn't defined?

Firstly, you're trying to remove numbers that are smaller than a given number. You can fix this by using property > num instead of property < num.
Next, you're not actually looking at all of the properties. Infact, prop is undefined. You need to use a for loop to check each property.
var obj = {
a: 8,
b: 2,
c: 'montana'
}
removeNumbersLargerThan(5, obj); console.log(obj); // --> { b: 2, c: 'montana' }
function removeNumbersLargerThan(num, obj) {
for (var property in obj) {
if (obj[property] > num) {
delete obj[property];
}
}
}

Related

is it possible to return the array with object property names? it's wired to ask to print the string without ' ' [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 2 years ago.
Write a function called myFun which has an object as its parameter and returns the name of properties of that object in an array. For instance, if it receives {a:1,b:3}, as its parameter, it should return [a, b], or if it receives {u:4, k:3, h:5}, it should return [u, k, h].
Note I am aware of Object.Keys(object) returns ['a', 'b', 'c']
//this function should return the name of the property
function myFun(object) {
object = {
a: 1,
b: 2,
c: 3
}
for (obj in object) {
console.log(obj);
}
}
myFun();
//testcase : console.log(myFun({a:6})[0]) which should return [a], is it
actually possible or am I asking the wrong question?
To get an array of object keys:
const keys = Object.keys(object);
To print them like you describe:
console.log(`[${keys.join(',')}]`);
Putting it together as a function:
function myFun(object) {
const keys = Object.keys(object);
return `[${keys.join(',')}]`;
}
This is the object's keys
var obj = {
a: 1,
b: 2,
c: 3
};
console.log(Object.keys(obj));

Destructure and retrieve the fully structured variable in one expression [duplicate]

This question already has answers here:
Destructure object parameter, but also have reference to the parameter as an object? [duplicate]
(2 answers)
Closed 3 years ago.
Is it possible to both destructure a variable and have access to the structured variable in the same call?
For example, what could I replace ??? below to get the desired output (and how else might I have to edit my code)
const foo = ({ a, b }) => {
console.log(a) // 1
console.log(b) // 2
console.log(???) // { a: 1, b: 2 }
}
const x = { a: 1, b: 2 }
foo(x)
My goal is knowledge and succinct code - I want to avoid const { a, b } = params as the first line of foo() in the case where I might need to pass the entire params object on.
If the first argument is an object whose reference you want, it's not possible - once you destructure an argument, there's no longer any way to reference to the full argument, only some of its properties.
It would be possible if the object and parts you wanted was part of a larger object, though, because then you can reference the property name alone (to get the object into a variable), and then reference it again to destructure, eg:
const foo = ({ obj: { a, b }, obj }) => {
console.log(a) // 1
console.log(b) // 2
console.log(obj) // { a: 1, b: 2 }
}
const obj = { a: 1, b: 2 }
foo({ obj })
Your original code could work to an extent if the object had a property that referenced itself, but that's pretty weird:
const foo = ({ a, b, obj }) => {
console.log(a) // 1
console.log(b) // 2
console.log(obj) // { a: 1, b: 2 }
}
const x = { a: 1, b: 2 }
x.obj = x;
foo(x)

Using an array to access (deeply) nested object properties [duplicate]

This question already has answers here:
How to use an array of keys to fetch the value from a Javascript object
(3 answers)
Closed 3 years ago.
Given javascript object:
obj = {
a: {
b: {
c: 3
}
}
}
I can access the deepest property as follows: obj['a']['b']['c'] or obj.a.b.c. Now I want to access this using an array ['a', 'b', 'c']. How can I access the same object property using this array?
Note: the method does not have to "safe", so no need to check for: typeError: cannot read property ... of undefined.
You can do this using reduce method and pass your object as accumulator param.
const obj = {
a: {
b: {
c: 3
}
}
}
const key = ['a', 'b', 'c'];
function get(obj, key) {
return key.reduce((r, e, i, a) => {
return r[e] || (a[i + 1] ? {} : undefined)
}, obj)
}
console.log(get(obj, key))

Check if nested key exists even if undefined [duplicate]

This question already has answers here:
Checking if a key exists in a JavaScript object?
(31 answers)
Closed 4 years ago.
Trying to figure out what the easiest way to write a function keyExisits that checks and arbitrarily nested key to see if it exists in an object and is undefined, vs does not exisit.
assume this obj
var obj = {
a: {
b: 1,
c: {
d: 2,
e: undefined
}
}
}
In this object the key a.c.e exists and is undefined, the key a.c.f does not exist
so
keyExists(obj, 'a.c.e') === true
keyExists(obj, 'a.c.f') === false
using lodash/underscore is ok
** UPDATE **
Lodash has works exactly like this
You can try following
var obj = {a: {b: 1,c: {d: 2,e: undefined}}};
function keyExists(o, key) {
if(key.includes(".")) {
let [k, ...rest] = key.split(".");
return keyExists(o[k], rest.join("."));
} else if(o) {
return o.hasOwnProperty(key);
}
return false;
}
console.log(keyExists(obj, 'a.c.e') === true)
console.log(keyExists(obj, 'a.c.f') === false)
Note: The above code will not work if there are any dots in the key name or you are using [] notation.

indexOf but for objects? [duplicate]

This question already has answers here:
What's the correct way to test for existence of a property on a JavaScript Object?
(3 answers)
Closed 6 years ago.
I want to look through an object and assign each of it's existent properties to a variable.
There are 4 possible properties. Some of the objects have all 4. Some might only have two.
How can I check if a particular property exists? Is there an equivalent of indexOf() for arrays but for objects instead?
Use the in keyword:
"key" in object
which returns true or false, depending if the object, or anything in its prototype chain, has that property.
You can also use object.hasOwnProperty("key"), which will only be true if the object has key as a property of itself, not its prototype. Example:
var object = {};
"toString" in object; // true
object.hasOwnProperty("toString"); // false
Note (as per #dandavis's comment) that if object has a custom property called hasOwnProperty, this gets thwarted; to work around this, use hasOwnProperty.call(object, "key"). Example:
var a = {hasOwnProperty: Boolean};
a.hasOwnProperty('name'); // true
hasOwnProperty.call(a, 'name'); // false
If you are only interested in properties set directly on the object (not accessible via the prototype chain) then hasOwnProperty will provide a boolean value, true, if an object has the specified property.
For example: testObject.hasOwnProperty('propertyToCheckFor') would return true if testObject.propertyToCheckFor exists, otherwise it would be false.
See the following code for a more expanded example:
var obj1 = {
a: 1
};
var obj2 = {
a: 1,
b: 2
};
var obj3 = {
b: 2,
c: 3
};
var obj4 = {
a: 1,
b: 2,
c: 3
};
// For dispaly purposes
document.write('<pre>' + JSON.stringify({
obj1: {
hasA: obj1.hasOwnProperty('a'),
hasB: obj1.hasOwnProperty('b'),
hasC: obj1.hasOwnProperty('c')
},
obj2: {
hasA: obj2.hasOwnProperty('a'),
hasB: obj2.hasOwnProperty('b'),
hasC: obj2.hasOwnProperty('c')
},
obj3: {
hasA: obj3.hasOwnProperty('a'),
hasB: obj3.hasOwnProperty('b'),
hasC: obj3.hasOwnProperty('c')
},
obj4: {
hasA: obj4.hasOwnProperty('a'),
hasB: obj4.hasOwnProperty('b'),
hasC: obj4.hasOwnProperty('c')
}
}, null, 2) + '</pre>');
var obj = {
foo: 1,
bar: 2,
baz: 3
}
Object.keys(obj).forEach(function(key) {
window[key] = obj[key]
})
console.log(foo, bar, baz)
Or in ES2015
const obj = {
foo: 1,
bar: 2,
baz: 3
}
function assignPrivateVars() {
let {foo, bar, baz} = obj;
console.log(foo, bar, baz);
}
assignPrivateVars();
You can use destructuring assignment. If value is not defined, variable will be set to undefined. You can also check if variable is defined after destructuring then delete variable by reference.
var data = {a:1, b:2, c:3};
var {a, b, c, d} = data; // `d`: `undefined`

Categories

Resources