79293305

Date: 2024-12-19 06:38:29
Score: 0.5
Natty:
Report link

Agree with the answer from @Ayantunji.

Still adding some more context by this post.

As we know, a JavaScript object is an associated array as well.

It may mean the following:

const plainObject = {
  firstItem: 'Good Morning',
  secondItem: 'to All',
  thirdItem: 'of you',
};

The above JavaScript object is also equivalent to the following associated array.

const associativeArray = [];
associativeArray['firstItem'] = 'Good Morning';
associativeArray['secondItem'] = 'to All';
associativeArray['thirdItem'] = 'of you';

However, the above array is not an ordinary JavaScript array, but it is an associated array. An ordinary array will only have numeric indexes. However, an associated array will only have string indexes as in this case.

Since a JavaScript object is an associated array as well, the following all references are valid.

console.log(plainObject['firstItem']);  // Good Morning
console.log(plainObject.firstItem);  // Good Morning
console.log(associativeArray['firstItem']);  // Good Morning
console.log(associativeArray.firstItem);  // Good Morning

And now answering to the question :

While accessing an object, its property must be hard coded in the source code as we have done above. However while accessing an object as an associated array, we have options :- it can be still hard coded as well as referenced by variables.

The following code shows the JavaScript object accessed as an associated array by referencing a variable.

const propsName = 'firstItem';
console.log(plainObject[propsName]);  // Good Morning
console.log(associativeArray[propsName]);  // Good Morning

Please also note that variable reference is not possible while accessing an object. The following two statements will result the value undefined.

console.log(plainObject.propsName);  // undefined
console.log(associativeArray.propsName);  // undefined

A special note:

The way you have tried the same is shown below. At present it does not meet the syntax of a template literal, therefore it is resulting an syntax error.

const href = info.${name}.href;

The syntax error may be rectified as below. However in that case, it will just result the string 'info.accruedinterest.href'. It will still not access the object and get its value.

const name = 'accruedinterest';
const href = `info.${name}.href`; // info.accruedinterest.href
Reasons:
  • Blacklisted phrase (1): Good Morning
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Ayantunji
Posted by: WeDoTheBest4You