Obtain selected values from a deeply nested object in JavaScript

I have a collection of objects, each structured as follows:

{
  "myFilters": [
    {
      "isMatch": false,
      "filters": [
        {
          "id": "aaaaaa",
          "version": "v1"
        },
        {
          "id": "kk",
          "version": "v1"
        }
      ]
    }
  ],
  "randomAttr1": null,
  "randomAttr2": []
}

Assume the above is an object within the result list.

My aim is to extract all the versions and append them as values to a new element relevant_versions, but with the condition that both the Id and version must match the URL parameters. Here's what I've tried:

for (let f of result) {
    f.relevant_versions = f.myFilters.filter(x=>x.filters    
    .filter(item=>(item.id == this.$route.params.filterId && item.version == this.$route.params.version))
    .map(fid => fid.version))
}

However, instead of just the versions, the entire myFilters element is being added. I believe I may be making a simple mistake here.

What would be the correct way to populate relevant_versions?

Edit: The desired output should resemble:

{
  "myFilters": [
    {
      "isMatch": false,
      "filters": [
        {
          "id": "aaaaaa",
          "version": "v1"
        },
        {
          "id": "kk",
          "version": "v1"
        }
      ]
    }
  ],
  "randomAttr1": null,
  "randomAttr2": [],
  "relevant_versions":["v1", "v1"]
}

An example route could be localhost:8080/filters/kk/v1. In this case, kk corresponds to this.$route.params.filterId and v1 to this.$route.params.version.

Answer №1

It is recommended to map the values in the myFilters object rather than filtering it directly to find matching versions

const result = [{"myFilters":[{"isMatch":false,"filters":[{"id":"aaaaaa","version":"v1"},{"id":"kk","version":"v1"}]}],"randomAttr1":null,"randomAttr2":[]}]

this.$route = {params:{filterId:"kk",version:"v1"}}

// this avoids mutating `results`
const modifiedResult = result.map(f => ({
  ...f,
  relevant_versions: f.myFilters.flatMap(({ filters }) =>
    filters.filter(({ id, version }) =>
      id == this.$route.params.filterId && version == this.$route.params.version
    ).map(({ version }) => version)
  )
}))

console.info(modifiedResult)
.as-console-wrapper { max-height: 100% !important; }


If aiming to alter result, consider replacing the top-level map with a forEach or utilize a for..of loop as seen in your question

result.forEach(f => {
  f.relevant_versions = f.myFilters.flatMap(...)
})

// or

for (let f of result) {
  f.relevant_versions = f.myFilters.flatMap(...)
}

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

Is there a way to prevent the onClick event from executing for a particular element in React?

Currently working with Material UI, I have a TableRow element with an onClick event. However, I now need to incorporate a checkbox within the table. The checkbox is enclosed in a TableCell element, which is nested within the TableRow. The issue arises wh ...

Selecting specific elements from an array in JavaScript can be achieved by using various methods and techniques

Currently working on a quiz incentive system where users earn rewards based on the number of correct answers they input. The example array below shows the possible range of correct answers: var rightAnswers = ['a', 'b', 'c' ...

Is it possible to include an argument in an unnamed function in Node.js without assigning it to a variable?

Coming from a C/C++ background, I've been struggling with grasping the syntax of node.js. After searching online for code examples to explain blocking and non-blocking operations, I stumbled upon a piece that has left me perplexed for hours. Despite m ...

An issue occurred with lodash during the construction of /@types/lodash/common/object.d.ts at line 1188, character 142: Expected '('

Things were going smoothly, but out of nowhere my build started failing. Here are the errors that are popping up: ERROR in /node_modules/@types/lodash/common/function.d.ts (852,68): ';' expected. ERROR in /node_modules/@types/lodash/common/commo ...

Organizing information into rows and columns with VueJS

I am currently working on organizing some data and I am looking for a way to present it in a table format with rows and columns using Vue Js. I want the display to look like this: https://i.sstatic.net/uEEbj.jpg The issue I am facing is that my current c ...

PHP Array Output: Understanding the Basics

I am relatively new to PHP and faced with a challenge. I have an array $companyStates = array("AR","TX","LA","OK","GA","NC","SC"); It contains a list of US states. My goal is to do two simple tasks with this array: 1) print the values in this format: ART ...

What steps should I take to ensure my navbar functions correctly?

I have recently designed a responsive navigation bar for my website, but I am encountering an issue. When the user reduces the browser size and tries to click the hamburger icon on the side, the navbar does not work as expected. The user needs to refresh t ...

Utilizing AJAX requests to send a JavaScript array to PHP script

After exploring numerous posts on this platform, (and even attempting to replicate code,) I am still unable to understand why this particular code is not functioning as expected. On the main page, there is a textbox where users can paste data. Once data i ...

Transforming JSON structure using JavaScript

Looking for some advice on restructuring my webservice response. Here's the current structure: {"rows":[ {"1","A Time to Kill", "John Grisham", "100"}, {"2","A Time to Kill", "John Grisham", "200"}, {"3","A Time to Kill", "John Grisham", ...

Ways to retrieve namespaced vuex within the router

I'm facing an issue while trying to access Vuex getters with namespaced modules inside the routers.js file. The getters are always returning a null value even though the user is logged in and the value should be true. Here is an example of the code: ...

Error occurs when passing a service as a parameter to a controller in AngularJS

After adding 'loginService' as a parameter to the controller in order to reference the service I want to use, I encountered an error that caused the rest of my angular functions to stop working. app.controller('loginController', functi ...

What is the best way to use JavaScript to conceal a section of a form div?

After receiving some code from a certain platform and implementing it to hide part of my form div element, I noticed that the element hides and unhides quickly when running in a browser. This rapid hiding and showing behavior occurs when clicking on the bu ...

Encountering a TypeError in Mongoose: Unable to access properties of undefined while trying to read 'find'

Encountering an issue with the error message, TypeError: Cannot read properties of undefined (reading 'find'), specifically pointing to this block of code: app.get('/Organizations', (req,res) => { Organizations.find({}).then((organiz ...

Learn how to use Vue to check for loaded resources such as initiators and assets. If all resources are loaded, the console will display "all resources done

What is the method to check if loading a resource (initiator, assets) returns a console.log("all resources done")? Click here for image description ...

Issue with Internet Explorer: Refusing to run javascript included in AJAX-loaded content

While loading AJAX content that includes a javascript function using the jQuery .load function with done() on completion, I am facing an issue. $('#content').load(a, done); function done() { if(pagejs() == 'function') { ...

Symfony2 requires clarification and direction when it comes to managing quantities in a shopping cart

My current challenge involves managing quantities in a shopping cart. I can easily add, delete, and view products in the cart, but am struggling with increasing or decreasing quantities if a user wants to purchase multiple units of the same product. BACKG ...

Changing the request body and then routing it through Node.js

I am new to Node.js. I have been working for two days on modifying the body of a Request in Node.js and forwarding it using the http-proxy module for proxying. My goal is to intercept a user's password within a JSON object, encrypt it, and then updat ...

Ways to automatically style the child divs within a parent div

I'm trying to figure out how to float a parent div with child divs of different widths and heights while maximizing the use of space and not being affected by absolutely positioned elements. For reference, here's an example: http://jsfiddle.net ...

Accessing a JSON string correctly using JavascriptSerializer in JavaScript

When working with JavaScript, I encountered an issue where the data retrieved from a data table and converted to javascriptSerializer was not refreshing correctly when changing dataset selection parameters. The problem occurred when trying to populate a ne ...

Encountering an issue where the $nuxt object is not recognized when utilizing $nuxt.route

I'm currently experiencing an issue with my nuxt routes that I'm using within a computed property. Everything was working perfectly fine until just 3 minutes ago when I suddenly started getting the error message $nuxt is not defined. Once I remov ...