Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation:

object.property
object['property']

Let's explore a scenario using the latter method:

const user = {
    firstName: 'John',
    lastName: 'Doe'
}
const prop = 'firstName';
console.log(user[prop]);  //"John"

Now, my question is about utilizing bracket notation for array properties where the value inside the brackets represents a path to an array. Consider the following example:

const user = {
    firstName: 'John',
    lastName: 'Doe',
    nicknames: [
        { id: 1, value: 'Johnny'}, 
        { id: 2, value: 'JD'}, 
        { id: 3, value: 'Dude'}
    ]
}
const prop = 'nicknames[2].value';
console.log(user[prop]);

With the console.log(), I intend to output JD. However, this approach fails as there is no property named nicknames[2].value within user;

So the question remains: How can bracket notation be effectively used in such scenarios involving array properties?

Answer №1

If you're hesitant to include lodash just for a single function, another approach could be to add a custom function to your object that offers the same functionality.

Below is an example snippet demonstrating how you can utilize the specified type of prop string mentioned in your query:

const user = {
    firstName: 'John',
    lastName: 'Doe',
    nicknames: [
        { id: 1, value: 'Johnny'}, 
        { id: 2, value: 'JD'}, 
        { id: 3, value: 'Dude'}
    ],
    byProp (path) {
      return path.split(/\].|\]\[|\[|\./) // split on [] or .
                 .map( el => el.replace(/\]$/,'')) // remove any trailing ']'
                 // loop over split-string to get element
                 // return undefined if the property does not exist
                 .reduce( (obj, el) => obj ? obj[el] : undefined, this);
    }
}

console.log(user.byProp('nicknames[2].value'));
console.log(user.byProp('nicknames[1][value]'));
console.log(user.byProp('firstName'));
console.log(user.byProp('firstName.undefined'));

Answer №2

Thanks to the helpful tip from @JanS, I managed to achieve my goal by utilizing lodash's get() function in the following way:

const propertyName = 'nicknames[2].value';
console.log(_.get(userObject, propertyName));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to dynamically delete React Router Link components after they have been clicked on?

When using React Router, how do I remove the div that contains a Link component or the Link component itself when it is clicked on and the routing is complete? For instance, consider an app structured in the following way: ==Header== ==Link1 Link2== Onc ...

Error when attempting to add data into MongoDB using Node.JS: "The type 'string' cannot be assigned to type 'ObjectId | undefined'."

Attempting to add a document to the collection results in an error when specifying the _id field of the added document. How can I insert a document with an _id that is not an ObjectId? The error occurs with the following code. Omitting the _id resolves th ...

Adding a personalized service into a separate service within Angular 2

I am having trouble injecting my own service into another service. While I can inject standard Angular services like Http without any issues, attempting to inject custom services results in an exception. For example, here is how MyService is set up: impo ...

Encountering an error message stating "Buffer is not defined" while working with gray-matter

Encountering an issue when trying to utilize gray-matter in Angular 9, the error message displayed is: ReferenceError: Buffer is not defined at Object.push../node_modules/gray-matter/lib/utils.js.exports.toBuffer (utils.js:32) at push../node_modul ...

How can I create a regex pattern that will exclude characters within parentheses?

While working on some regex, I encountered a bug: The scenario is as follows: I have this string - for example "+1/(1/10)+(1/30)+1/50" and I applied the regex /\+.[^\+]*/g to it, which worked perfectly giving me ['+1/(1/10)&apos ...

The promise callback in Angular2 is unable to access this

This snippet of code is quite odd, but it resides within a service context: constructor() { gapi.load('client:auth2', this.loadGoogleApi); } private loadGoogleApi() { // Array of API discovery doc URLs for APIs used by the quickstart ...

Typescript: Implementing the 'types' property in a function returned from React.forwardRef

I'm exploring the option of adding extra properties to the return type of React's forwardRef function. Specifically, I want to include the types property. Although my current implementation is functional, given my limited experience with TypeScri ...

After making edits, the JQGrid will automatically refresh the data with the updated information retrieved from the

My Jqgrid is in need of some editing. I have successfully set it up to save data after editing, but there is an issue with the grid not refreshing with the database data once it's saved. For instance, the version field gets updated automatically by th ...

The element 'x' is implicitly bound with a type of 'any'

I've been exploring the world of Nextjs and TypeScript in an attempt to create a Navbar based on a tutorial I found (). Although I've managed to get the menu items working locally and have implemented the underline animation that follows the mou ...

The `encodeAddress()` function in Google Geocode is used to ge

Encountering issues with extracting latitude and longitude values from Google's response. Google is providing XML-like data: "location" : { "lat" : 53.55914120, "lng" : 10.00923520 }, I am trying to parse this using var r = results[0].geome ...

Vue.js mobile app may show a loaded DOM that remains invisible until the screen is tapped

I am facing a peculiar issue that has me stumped. On my mobile device, my page initially loads like this homepage However, once I tap the screen, all the components suddenly appear. Is there a way to simulate a click on my mobile? I'm struggling to u ...

Analyzing JSON information and presenting findings within a table

Requesting user input to generate a JSON object based on their response. Interested in showcasing specific details from the object in a table format for user viewing. Questioning the efficiency and clarity of current approach. My current progress: In HTM ...

Azure function indicates a successful status despite receiving a result code of 500

I have an Azure function containing some logic with a basic try-catch structure (code shortened). try { // perform logic here that may fail } catch (ex) { context.log(`Logging exception details: ${ex.message}`); context.res ...

Is there a specific type in typescript that represents every iterable object?

We have a unique function shown below: export const transformUndefinedToNull = (obj) => { const convert = (o) => { Object.keys(o).forEach((key) => { const value = o[key]; if (value === undefined) { o[key] = null; } ...

What is the best way to retrieve a document from a collection in a Meteor application?

My experience with mongodb is very limited, so I need help on how to retrieve a document from a meteor collection. I am trying to check if a document exists for the user and update it with an object. if (Saves.find({_id: Meteor.userId()}).fetc ...

What is the method for referencing a subtype within an established type?

When working with React-native, I came across a component called FlatList which includes a property known as ListHeaderComponent. My question is how to specify the type of this property without having to manually copy and paste the original type. Currentl ...

Poor quality picture captured with the use of the getUserMedia() Javascript function

Is there a way to improve the resolution of mobile phone camera screenshots taken with JavaScript's getUserMedia function? if (navigator.mediaDevices) { navigator.mediaDevices.getUserMedia({ video: { width: { min: 1280, }, heig ...

Perplexed by the implementation of "require(...)" in TypeScript

After reading several blog posts, my understanding of TypeScript modules remains confusing. I have worked with three different modules (all installed via npm) and encountered varying behavior: (1) Importing and using Angular 2 from npm required me to add ...

Learn how to retrieve JSON data from the Yahoo Finance REST API using Angular 2

Currently, I am in the process of developing an application that needs to fetch data from the Yahoo Finance REST API. To retrieve a table for the symbol "GOOG," I have implemented the following code: export class ActService{ act = []; url = 'http ...

Jquery Enhancement for Navigation

Recently, I have implemented a header and footer navigation on my website. The header navigation consists of 1 UL (unordered list), while the footer navigation comprises 5 ULs. My goal is to align the first child of each UL in the footer navigation with th ...