2

the _.get() function allows you to use a string to deep get value from Json object. However it gets value and not reference, is an equivalent command (or diff way) to get reference to Json object

example:


var object = { 'a': [{ 'b': { 'c': 3 } }] };

const r = _.get(object, 'a[0].b');
r <<< is new object not a ref.

thanks,

Sean

born2net
  • 24,129
  • 22
  • 65
  • 104
  • 1
    What do you mean by reference? A reference to the number `3`? – ibrahim mahrir Nov 12 '19 at 18:15
  • 1
    You can get the object `{ 'c': 3 }` by using `var ref = _.get(object, 'a[0].b')`. `_.get` will return a reference to that object. Changing `ref.c` will change the original object – ibrahim mahrir Nov 12 '19 at 18:16
  • Sorry I mean reference to the object, I will fix the example – born2net Nov 12 '19 at 18:17
  • 1
    _"`r` is new object not a ref"_. Well try changing it's properties and notice what happens to the original object. `r` references the object `{ 'c': 3 }` from the original object. This can be proven by checking `object.a[0].b === r` – ibrahim mahrir Nov 12 '19 at 18:19
  • according to my tests and this https://github.com/lodash/lodash/issues/2638 it's not the case – born2net Nov 12 '19 at 18:19
  • 1
    The issue in the github link is totaly different. They are trying to get the root object itself. You are trying to get a nested object which does return a reference: https://repl.it/repls/UselessVeneratedRobodoc – ibrahim mahrir Nov 12 '19 at 18:23
  • I tried it with nested and had same result, changing the result of my _.get did not change the original Json. – born2net Nov 12 '19 at 18:25
  • 1
    https://repl.it/repls/UselessVeneratedRobodoc – ibrahim mahrir Nov 12 '19 at 18:26
  • 1
    BTW, you can't replace a variable and expect the original object to get affected. I mean `r = { some: "other object" }` will not work. It will change the reference itself. `r` will not reference your object any more, it will reference the new one you just assigned. References just don't work like that. – ibrahim mahrir Nov 12 '19 at 18:27
  • 1
    BTW #2: javascript doesn't really have references like another language like c# or c++ does: https://stackoverflow.com/q/518000/9867451 . If it did and `r` was truly a reference, then replacing `r` with a new object would affect the original object – ibrahim mahrir Nov 12 '19 at 18:31
  • This example is pretty much what you are trying to do: https://stackoverflow.com/a/3638034/9867451 – ibrahim mahrir Nov 12 '19 at 18:35

1 Answers1

4

The _.get function does not create a new object. It is already returning a "reference".

const object = { 'a': [{ 'b': { 'c': 3 } }] };

const r = _.get(object, 'a[0].b');

console.log(r === object.a[0].b); // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
Jake Holzinger
  • 5,783
  • 2
  • 19
  • 33