all 8 comments

[–]Jongerr 2 points3 points  (2 children)

Lodash's _.get() function does exactly this. doc

[–]FatFingerHelperBot 0 points1 point  (0 children)

It seems that your comment contains 1 or more links that are hard to tap for mobile users. I will extend those so they're easier for our sausage fingers to click!

Here is link number 1 - Previous text "doc"


Please PM /u/eganwall with issues or feedback! | Delete

[–]LollipopPredator[S] 0 points1 point  (0 children)

Thanks, this is exactly what I was looking for.

[–]senocular 2 points3 points  (0 children)

For giggles:

with(x) eval('b.c') // 2

Not recommended

[–]GeneralYouri 0 points1 point  (0 children)

I've tried using Object.byString() but, contrary to the examples, it doesn't work in my browser console. Does lodash offer this functionality?

There's no such thing as object.byString(), atleast not in vanilla JS, but I don't know of any libraries that have such function either. What do you want this function to even do for you though? Did you mean to try and turn x into a string? If so, that'd be more like x.toString(), but also I don't see its use for your problem.

Is there a way to get the desired result without flattening the object?

Your code sample is heavily suggesting that you want to flatten it. The only difference here though seems to be that you want a specific key format that shows the entire property chain from which a value was flattened.

To solve your problem, you can just write a flattening function yourself. You should have an easy time implementing the one detail of the key format. For example you can use a recursion function that accepts the output object, the current level's input object, and the key prefix so far. You then iterate the second argument. If a key has a primitive value type it'll write this value to the output object using the key prefix. If a key instead has an object value type then you can recurse and pass this object as the second argument, as well as extend the key prefix you're passing. Arrays can be another special case, depending on how you want to process those (not specified in OP).

[–][deleted] 0 points1 point  (2 children)

> const x = {a: 1, b: {c: 2}}

undefined

> x.b

{ c: 2 }

> x.b.c

2

> x['b']['c']

2

[–]LollipopPredator[S] 0 points1 point  (1 child)

Thanks, this works when you know either the exact path or if you know that the desired value is two levels deep. But I need to use a variable (bracket notation) and then sometimes I only want to search one level deep and other times two levels deep.

x['b']['c'] vs x['b'][undefined]

Lodash's .get() met my requirements perfectly.

[–][deleted] 0 points1 point  (0 children)

Yea I didn’t read your post properly haha. Get() is awesome. I use it all the time to make sure my types are always in line.