2

Let's say I have a simple object a = {b: 2}. I know of two ways to get the value of property b of a:

Dot notation: a.b // 2

and

Bracket Notation: a['b'] // 2

Practicality aside, does there exist any way to get the value of b from object a without using either of these two methods (dot notation and bracket notation)? MDN's page on Property Accessors only lists the 2 methods.


It's just a curiosity I had. I know there exist obscure ways to call functions without parenthesis, eg

parseInt`5.1`

I wanted to see if a similarly obscure thing was possible for Property access.

Phil
  • 157,677
  • 23
  • 242
  • 245
Lucien
  • 123
  • 8
  • 1
    Is there a reason for this question? – Phil Sep 21 '18 at 01:37
  • It depends upon what you are trying to do. For example, in your limited example `a[0] //2` as well. – Sablefoste Sep 21 '18 at 01:39
  • @Sablefoste did you try executing that? – Phil Sep 21 '18 at 01:39
  • @phil, right, it gives `undefined`. But also the point is it could be used in a reference. For example: https://stackoverflow.com/a/24061635/1408137 – Sablefoste Sep 21 '18 at 01:49
  • @Sablefoste for a plain object? I don't think so – Phil Sep 21 '18 at 01:50
  • @Phil It's just a curiosity I had. I know there exist obscure ways to call functions without parenthesis (ex. double backticks). I wanted to see if a similarly obscure thing was possible for Property access. – Lucien Sep 21 '18 at 01:56
  • You should probably explain that in your question. Right now, it just seems pointless since brackets and dots work just fine. Also, what's this double-backtick syntax you speak of? – Phil Sep 21 '18 at 01:57
  • `parseInt\`5.1\` // 5` – Lucien Sep 21 '18 at 02:00
  • Don't overlook the power of bracket notation, though. There is so much that can be accomplished with that feature. – Ben Steward Sep 21 '18 at 02:02
  • @phil My favorite example of how weird javascript is involves backticks: `Function\`$${\`alert($$)\`}$$\`\`$${\`wat\`}$$\`` – Lucien Sep 21 '18 at 02:04
  • This is hilarious; I don't think there is a reason, but a definitive reference may be helpful for someone??? – Rafael Sep 21 '18 at 02:18
  • @Rafael Are you talking about the alert statement? Because if so, I'd be happy to explain how it works! Although the comment section might not leave enough space. – Lucien Sep 21 '18 at 02:45

4 Answers4

5

Don't forget Object.getOwnPropertyDescriptor():

const object1 = {
  property1: 42
}

const descriptor1 = Object.getOwnPropertyDescriptor(object1, 'property1');
console.log(descriptor1.value);//42

It doesn't search through the prototype chain, but it works on immediate properties and worth noting, for you can make recursive functions searching the prototype chain with it :)

Rafael
  • 7,605
  • 13
  • 31
  • 46
  • Thanks! This is what I was looking for, too. Bracket and dot-notation usually work fine, but sometimes you need to be able to hack and mock stuff for testing. – Julian Sep 01 '23 at 12:32
4

First thing that springs to mind is Object.values

const a = {b: 2}

Object.values(a).forEach(v => {
  console.info(v)
})

But how would you know what key you're accessing?

There's also Object.entries() I suppose

const a = {b: 2}

Object.entries(a).forEach(entry => {
  // entries are [key, value] arrays
  let value = entry.pop()
  let key = entry.pop()
  console.info(key, ':', value)
})

Note: I used Array.prototype.pop() so as not to use "bracket notation".

Phil
  • 157,677
  • 23
  • 242
  • 245
4

This is not exactly the same as accessing a property, but it’s nevertheless a sneaky way to get at an object’s contents if you are using the latest JS (es6+). All the hip JS kids are doing it these days.

const { b } = a
console.log(b) // 2

This is called destructuring, it works with objects and arrays, and you can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Ben Steward
  • 2,338
  • 1
  • 13
  • 23
  • And here I am using functions like some kind of grandpa. Nice answer :D – Phil Sep 21 '18 at 01:55
  • Both answers are really insightful, but I'll accept this one since it avoids using any dot syntax or bracket notation entirely. Now I wonder if there is a way to use destructuring if we can't type the variable name directly, but rather have a string with its name. Like: `const a = {b: 2}; const c = 'b'; // somehow access b using destructuring using the variable c`. Interesting stuff to consider. Anyway, thanks! – Lucien Sep 21 '18 at 02:10
  • @Lucien you sure can... `let { b: c } = a`. This is handy for property names that don't make good variables, eg `{ '.id': 2 }`. Edit: I may have misunderstood – Phil Sep 21 '18 at 02:26
  • 1
    These are the droids you are looking for: https://tylermcginnis.com/videos/computed-property-names/ – Ben Steward Sep 21 '18 at 02:29
0

Here's an implementation of lodash 'get' and 'set' without using dot or bracket notation; useful for passing security scans.

https://jsfiddle.net/5amtL8zx/17/

/* lodash implementation of 'get', 'set', and 'unset' without dot or bracket notation
  * - supports getting and setting 'prop1.2' array element but not with brackets: 'prop1.[2]'
  */
isObjectKey = (obj, key) => {
  return Object.getPrototypeOf(obj) === Object.prototype && /string|number/.test(typeof key);
}

isArrayNumber = (obj, key) => {
  const isKey = /string|number/.test(typeof key), path = isKey ? String(key).split('.') : [], prop = isKey && path.length > 1 ? path.shift() : '';
  return Object.getPrototypeOf(obj) === Array.prototype && isKey && !isNaN(prop);
}

isValid = (obj, key) => {
  const isObj = isObjectKey(obj, key), isArr = isArrayNumber(obj, key);
  return isObj || isArr;
}

define = (obj, key, value) => {
  Object.defineProperty(obj, String(key), { value, writable: true, configurable: true, enumerable: true  });
}

get = (obj, key, value) => {
  if (!isValid(obj, key)) {
    return undefined;
  }
  let path = String(key).split('.'), prop = path.shift(), result = new Map(Object.entries(obj)).get(prop);
  return path.length && typeof result !== 'undefined' ? get(result, path.join('.'), value) : result || value;
}

set = (obj, key, value) => {
  if (!isValid(obj, key)) {
    return undefined;
  }
  let path = key.split('.'), prop = path.shift();
  if (!(prop in obj)) {
    define(obj, prop, {});
  }
  const result = get(obj, prop);
  return path.length && isValid(result, path.join('.')) ? set(result, path.join('.'), value) : define(obj, prop, value);
}

unset = (obj, key) => {
  if (!isValid(obj, key)) {
    return undefined;
  }
  let path = key.split('.'), prop = path.shift();
  if (!(prop in obj)) {
    return undefined;
  }
  if (path.length) {
    let result = get(obj, prop);
    result = unset(result, path.join('.'));
    set(obj, prop, result);
    return obj;
  } else {
    const { [prop]: remove, ...rest } = obj;
    return rest;
  }
}

let obj = {};
set(obj, 'prop1.prop2', 'value1');
console.log(Object.entries(obj));
console.log(get(obj, 'prop1.prop2'));
const prop1 = get(obj, 'prop1');
set(prop1, 'prop2', 'value2');
console.log(get(obj, 'prop1.prop2'));
set(obj, 'prop3', [1, 2, 3]);
console.log(get(obj, 'prop3'));
console.log(get(obj, 'prop3.2'));
console.log(get(obj.prop3, 0));
set(obj, 'prop3.3', 4);
console.log(get(obj, 'prop3.3'));
set(obj, 'prop4', [{'name': 'Bob'}]);
console.log(get(obj, 'prop4.0'));
unset(obj, 'prop4.0.name')
console.log(get(obj, 'prop4.0'));
//[["prop1", {
//  prop2: "value1"
//}]]
//"value1"
//"value2"
//[1, 2, 3]
//3
//1
//4
//{
//  name: "Bob"
//}
//{ ... }
Ron Roth
  • 1
  • 1