Bracket notation accepting arrays

I don't know why, but this made me think about your Overloadable data accessor operator proposal @theScottyJam.

With the only difference that the @[] operator could not only be used to enable overloading access on the object, but also to accept any object type as a key (in contrary to the normal [] accessor that directly calls .toString on the object it receives, so that it is always a string).

The advantage would be that any given object would stay intact inside @[] custom get / set handlers, whereas in the proxy solution, objects like ({a: 1, b:2}) would have been already stringified to "[object Object]", and so being unusable inside the proxy get / set handlers.

Also, we would explicitly indicate that we want to treat the object as is (and not use its stringified value), so it would be more understandable than using proxies under the hood.

Here is an example to show how it could work for this use case:

// Custom getter function
const getter = function (path) {
  let value = this;
  path.forEach(key => { value = value?.[key]; });
  return value;
}

// Custom setter function
const setter = function (path, value) {
  let target = this;
  let lastKey = path.at(-1);
  path.slice(0, -1).forEach(key => {
    if (typeof target[key] !== "object") target[key] = {};
    target = target[key];
  });
  target[lastKey] = value;
}


// The object, with overloaded data accessor operator
const obj = {
  // Data accessor overloads
  [Symbol.getDataValue]: getter,
  [Symbol.setDataValue]: setter,

  // Data
  name: {
    fName: "John",
    lName: "Smith",
  },

  // Just to test
  "name,fName": "test",
}


// We can now use the `@[]` operator to get / set values using an array
const path = ["name", "fName"];
obj@[path] = "Jane";
obj@[path] += "y"; // value becomes "Janey"

// Normal `[]` accessor still works as usual
obj[path] === "test"
3 Likes