Check if nested key exists even if undefined [duplicate] - javascript

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.

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

Is there a way to get all keys inside of an object (including sub-objects)? [duplicate]

This question already has answers here:
Get all keys of a deep object in Javascript
(7 answers)
Closed 3 years ago.
Currently, I'm trying to get all the keys of an object, including the sub-objects.
I know that
Object.keys(obj)
returns the keys of the object, but not the keys of the objects inside of it.
So, for example, I got following object:
let exampleObject =
{
a: "value",
b: "value",
c: 404,
d: {
e: "value",
f: "value"
}
}
NOTE: The d key might change its name, so it won't work to use something like Object.keys(obj.d).
How do I get e and f in my total list of keys existing inside an object?
You could use flatMap to recursively get the keys like this:
let exampleObject={a:"value",b:"value",c:404,d:{e:"value",f:"value"}};
const getKeys = obj => Object.keys(obj).flatMap(k => Object(obj[k]) === obj[k]
? [k, ...getKeys(obj[k])]
: k)
console.log(getKeys(exampleObject))
If flatMap is not supported, use reduce like this:
function getKeys(obj) {
return Object.keys(obj).reduce((r, k) => {
r.push(k);
if(Object(obj[k]) === obj[k])
r.push(...getKeys(obj[k]));
return r;
}, [])
}
The Object(obj[k]) === obj[k] checks if the property is an object and it is not null. Because, typeof null === "object"
You can try that using recursion.
Create a wrapper function getAllKeys() and create an empty array inside that.
Now create another function getKeys() which takes object and which will be called recursively.
Inside getKeys() loop through the keys using for..in.
push() the key into empty array created in wrapper function.
Check if the typeof key is "object" then call the function recursively on that.
let exampleObject =
{
a: "value",
b: "value",
c: 404,
d: {
e: "value",
f: "value"
}
}
function getAllKeys(obj){
let res = []
function getKeys(obj){
for(let key in obj){
res.push(key);
if(typeof obj[key] === "object"){
getKeys(obj[key])
}
}
}
getKeys(obj);
return res;
}
console.log(getAllKeys(exampleObject))

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

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

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];
}
}
}

Shorthand for creating object with same field [duplicate]

This question already has answers here:
One-liner to take some properties from object in ES 6
(12 answers)
Closed 5 years ago.
const json = {
a: 1,
b: 2,
c: "HI"
}
Is there a way to just pass in {a : 1} to function?
var someReturn = aOnly({a : json.a});
I am not sure if destructuring/constructuring of ES6 solves this problem. I can't seem to find the right syntax after reading several ES6 destructuring example.
EDIT
Nothing is wrong with the code I am just asking if there is a syntax to just extract "a" only from JSON without redundantly doing
{a : json.a }
the implementation of aOnly function is not the focus here
You can use ES6 object destructuring on object passed as parameter to pick specific property.
const json = {
a: 1,
b: 2,
c: "HI"
}
function aOnly({a}) {
return a;
}
var someReturn = aOnly(json);
console.log(someReturn)
Thank you I have figured out the right syntax. The initial mistake I was doing was trying to construct directly using { json.a }, hoping that this will automatically turn into { a : json.a} but the right way is do destruct first and construct later.
var json = {
a : "ASDF",
b : 123,
c : "Test"
};
const {a, b, c} = json; // destructing
var aObject = aOnly({a}); // constructing
var bObject = bOnly({b});
var cObject = cOnly({c});
console.log (aObject);
console.log (bObject);
console.log (cObject);
function aOnly(a) { return a; }
function bOnly(b) { return b; }
function cOnly(c) { return c; }

Categories

Resources