deoxxa / dotty

Access properties of nested objects using dot-path notation
BSD 3-Clause "New" or "Revised" License
127 stars 20 forks source link

Add support for arrays #12

Open ragulka opened 10 years ago

ragulka commented 10 years ago

It'd be great if dotty could work with nested arrays as well, for example, with something like this:

{
  some: 'property',
  other: [{ properties: true }, { properties: true }]
}
jgrund commented 10 years ago

What about:

  var dotty = require('dotty');

  var obj = {
    some: 'property',
    other: [{ properties: true }, { properties: true }]
  };

  dotty.get(obj, 'other.0'); // { properties: true }
  dotty.get(obj, 'other.1'); // { properties: true }

The syntax is a little awkward, but seems to work.

kbariotis commented 8 years ago

Since the goal of this project is to access specific properties I would suggest this feature to return all objects from the array, but only with the specified fields.

 var dotty = require('dotty');

  var obj = {
    some: 'property',
    other: [
      { 
        property1: true, 
        property2: false 
      }, 
      { 
        property1: true, 
        property2: false 
      }
    ]
  };

  dotty.get(obj, 'other.property1'); // [{ property1: true }, { property1: true }]
deoxxa commented 8 years ago

The actual original goal of this project was to replace all the places where I had code like this:

var something = null;
try {
  something = a.b.c.d.e;
} catch (e) { something = 'default'; }

x.y = x.y || {};
x.y.z = something;

with this kind of thing:

dotty.put(x, 'y.z', dotty.get(a, 'b.c.d.e') || 'default');

Clearly it does more now than it did then, but this is a pretty major departure from the existing API. It might be better implemented as a different method, or even as another module that perhaps builds atop this?

kbariotis commented 8 years ago

Something I have in mind and wrote the above comment is to replicate the MongoDB field selection on an object.

So with an object like this:

var object = {
  "name": {
    "first_name": "Kostas",
    "last_name": "Bariotis"
  }
}

I could easily create an exact same object that only contains the first_name attribute.

Do you think dotty would be a nice fit for this kind of job?

Thanks @deoxxa :)

brentchow commented 8 years ago

+1