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))
Related
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 2 years ago.
I'm fairly new to Javascript Object. I've defined a non-destructive function to update an object like this:
function updateObjectWithKeyAndValue(object, key, value) {
return Object.assign({}, object, { key: value });
}
let object = {a: 1};
console.log(updateObjectWithKeyAndValue(object, 'b', 2));
console.log(object);
I'm getting the return value of the function as { a: 1, key: 2 } instead of { a: 1, b: 2 }. Is there something I'm not doing right? Thanks...
{ key: value } is an object with a property named “key”. To name the property according to the value in the variable key, use a computed property name:
{ [key]: value }
If your JavaScript environment supports object spread, the whole thing can be written as:
return { ...object, [key]: value };
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));
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))
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.
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];
}
}
}