The issue of finding a nested object key using dot notation in Vue JS with lodash is resulting in

I am facing an issue where I am unable to retrieve a value for a nested object key from the eligibility array. The value is coming out as undefined and I need help in figuring out what mistake I am making.

Here is the given array:

const eligibilityCriteria = [
  { field: 'loan.amount', operator: '>=', value: 1000 },
  { field: 'loan.term', operator: '>=', value: 1 },
  { field: 'applicant.birthday', operator: '>=', value: 40 },
  { field: 'applicant.isHomeowner', operator: '==', value: false }
]

The objective is to extract the value for loan.amount from a nested object:

The nested object available is (retrieved from the store)

application: {
  meta: {
    brand: '',
    version: '',
    affiliate: '',
    affiliate_full: '',
    campaign: '',
    client_hostname: '',
    client_href: '',
    client_origin: '',
    client_useragent: '',
    client_ip: '127.0.0.1',
    icicle_hash: ''
  },
  loan: {
    amount: 500,
    term: null,
    purpose: null
  }
}

The current function looks like this:

checkEligibility () {
  const eligibilityCriteria = [
    { field: 'loan.amount', operator: '>=', value: 1000 },
    { field: 'loan.term', operator: '>=', value: 1 },
    { field: 'applicant.birthday', operator: '>=', value: 40 },
    { field: 'applicant.isHomeowner', operator: '==', value: false }
  ]

  for (const [index, offer] of this.datasets.offers.entries()) {
    const eligibility = eligibilityCriteria

    if (eligibility) {
      for (const [ci, criteria] of eligibility.entries()) {

        // Issue: Unable to fetch the value, returns undefined
        const field = _.findKey(this.$store.state.application.application, criteria.field)
      }
    }
  }
}

Can you point out what I might be overlooking?

Answer №1

It seems like there may be some confusion regarding the functionality of _.findKey(). You can read more about what it does here.

To clarify, this method is similar to _.find but instead of returning the element itself, it returns the key of the first element for which the predicate function returns a truthy value.

Please refer to Example 2 in the code snippet below for better understanding.

If you need to access the value from an object at a specific path, consider using _.property() as shown in Example 2.

const eligibilityCriteria = [
  { field: 'loan.amount', operator: '>=', value: 1000 },
  { field: 'loan.term', operator: '>=', value: 1 },
]

const application = {
  loan: {
    amount: 500,
    term: 2,
    amount2: 0,
  }
}

// example 1
// outputs "loan"
console.log(_.findKey(application, "amount"))     
// outputs undefined - there is no key in application object that has property chain "loan.amount"
console.log(_.findKey(application, "loan.amount"))
//  outputs undefined - "amount2" key is there but the value is falsy
console.log(_.findKey(application, "amount2"))     

// example 2
for (const [ci, criteria] of eligibilityCriteria.entries()) {
  console.log(criteria.field, _.property(criteria.field)(application))
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f53505b5e4c577f0b110e08110d0e">[email protected]</a>/lodash.min.js"></script>

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

The native V8 syntax exclusive in Chrome

Is there a similar special flag like --allow-natives-syntax in Google Chrome? Can this kind of information be accessed using devtools or another method within the browser? // example code snippet var person = { name: 'Alice', age: 30 }; console ...

Ways to retrieve the identifier of the uploaded document in GridFs for linking with another model

After creating a GridFS and uploading an image using the code snippet below: app.post("/upload", upload.single("photo"), function(req, res) { res.redirect("/images"); }) I also have a separate model for users: var userSchema = new mongoose.Schema({ ...

Node.js Error: The object does not have the specified method

Recently, I dived into the world of node.js by following a fantastic tutorial on node.js, express, and mongodb from Howtonode. However, I encountered an error that doesn't seem to have been addressed in the comments section. The last comment was made ...

The feature to dynamically insert additional fields includes two dropdown menus (one for selecting category and one for product) and an input box for entering a price

I am looking to dynamically populate two dropdown menus and an input box based on data fetched from a database. The first dropdown should populate categories, the second dropdown should display products based on the category selected, and the input box sho ...

TS does not recognize the term "Response"

After I launch my function, why does the console throw this error: ReferenceError: Response is not defined Here's my code snippet: @Get('/download/:fileId') @Header('Content-Type', 'application/vnd.openxmlformats-offi ...

Transform a nested array of objects into a distinct set of objects based on the data in JavaScript or TypeScript

I have a unique situation where I am dealing with a double nested array of objects, and I need to restructure it into a specific array format to better align with my table structure. Here are the current objects I'm working with and the desired resul ...

Setting a specific time for a div element with opacity: A step-by-step guide

Is there a way to adjust the timing for the appearance of the add-to-cart when hovering over the product-list-item? Currently, it appears when I hover over the item and disappears when I move my mouse away. .product-list-item { position: relative; w ...

mongoose populate method does not return the expected results

My Project Objective I am currently in the process of creating a travel booking platform for a transportation company. One of the key features I am working on is displaying the name of the individual who made the booking on a specific page within the webs ...

What is the best approach for migrating event bus functionality to Vuex store?

At the moment, I have set up an event bus to trigger methods in specific Vue components from other unrelated components. With a fully functional Vuex store in place, my goal is to eliminate the need for the event bus and transition this functionality to t ...

Vue.js Multiselect issue

I have been trying to debug this error for 2 days now and I have tried multiple solutions without any success. I am working with vue.js version 2.1.10 and laravel 5.4, but I can't seem to figure out what is causing this bug. Here is my template.vue fi ...

Having trouble with querySelector or getElementById not functioning properly?

Currently, I am in the midst of developing an experimental web application that features a quiz component. For this project, I have implemented a Python file to handle the questions and quiz functionalities. However, I have encountered an issue with the Ja ...

When utilizing *NgIf, the button will be shown without the accompanying text being displayed

When trying to display either a confirm or cancel button based on a boolean set in my component.ts, I implemented the following code in my HTML: <mat-dialog-actions class="dialog-actions"> <button class="cancel-btn" ...

What are some effective strategies for resolving the persistent issue of Visual Studio Code warnings, MDN Reference difficulties, and other challenges?

Is there a way to turn off TypeScript warnings and completely disable TS in Visual Studio Code for standard JavaScript files while using SvelteKit? I typically opt out of using TS when starting a new project. Furthermore, is it possible to get rid of the ...

Sending a picture through AJAX using the camera feature of p5.js

Currently, I am exploring the camera functionality of p5.js to capture video. However, I am facing a challenge when trying to upload these images to a server using ajax. I am unsure about how to convert a p5.js Image object into a suitable format for trans ...

Dynamically add the <script> tag to the HTML document

Is there a way to dynamically append the <script></script> tag, using jQuery or pure JavaScript, along with a callback function? There are two crucial things to consider: 1) The <script> tag may contain more attributes than just 's ...

The swap feature in drag-and-drop does not have a defined function

I am currently developing a to-do app that utilizes drag and drop functionality to reorder items in the list. However, I have encountered an issue where swapping elements works perfectly for the first five elements but throws errors when dealing with the s ...

Transmit a PDF byte array from JavaScript to PHP using Ajax, then utilize the PHP file to send an email

I am facing a particular issue. Currently, I am utilizing the pdf-lib library for JavaScript to generate a PDF. The last step involves creating a uint8array: const pdfBytes = await pdfDoc.save() My goal is to transmit these pdfbytes via AJAX to a PHP fi ...

Retrieving intricate JSON data from a specific web address

I need assistance in extracting and printing the date value from the JSON content available at the specified URL. Specifically, I am looking to retrieve the date value of "data.content.containers.container.locationDateTime" only if the "data.content.conta ...

Utilizing AngularJS filter method to populate data

Just beginning my journey with Angular js, I've got this snippet of code that is responsible for binding data to the div element, app.filter("myfilter", function () { return function (data, catName) { if (angular.isArray(data) && angular ...

What could be the reason for Sequelize to completely replace the record when updating in a put request?

I've been attempting to implement an "edit" feature within my project, but I've hit a roadblock in the process. Here's a snippet of the put request code: export const updateEvent = (event, id) => (dispatch, getState) => { request ...