Filtering data dynamically in a nested array of objects using JavaScript

My task involves utilizing a dynamic array named var arr = ["key1","key2","key3"]. The goal is to filter an array of objects using this array. Here’s an example:

var obj = [{"key1":{"key2":{"key3":5}}},{"key1":{"key2":{"key3":7}}},{"key1":{"key2":{"key3":8}}}] 

I need to filter the objects so that "key3" equals 5. How can I accomplish this using plain vanilla JavaScript?

Answer №1

To streamline the process, you can use the keys to narrow down the object and retrieve the desired value for comparison.

var fetchValue = (keys, obj) => keys.reduce((o, k) => o[k], obj),
    keys = ["key1", "key2", "key3"],
    array = [{ key1: { key2: { key3: 5 } } }, { key1: { key2: { key3: 7 } } }, { key1: { key2: { key3: 8 } } }],
    result = array.filter(o => fetchValue(keys, o) === 5);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

jQuery and HTML: Need help enabling an <input> or <select> element?

Currently, I am using Mozilla Firefox 14.0.1 and Google Chrome 20.0.1132.57 (which I believe is the latest version). The code I am working with looks like this: http://jsfiddle.net/SVtDj/ Here is what I am trying to accomplish: Type something into inpu ...

Is Angular automatically assigned to `window.angular` on a global level when it is loaded as a CommonJS module?

When I import Angular 1.4 in my Webpack build entry point module as a CommonJS module using var angular = require("angular");, it somehow ends up being accessible in the global namespace of the browser (as window.angular). Upon examining the source code o ...

Retrieving Substring before Specific Character in PHP

Imagine I have a String like this: $b = 'grapes, pineapple & fruit seller offered by flipkart from usa'; From this sentence, what I need are 3 specific words: grapes pineapple fruit seller The first word can be extracted using the explod ...

Multipart form data processing without specifying files

I need help with uploading an image using node.js, express, and multiparty. My code is as follows: HTML <!DOCTYPE html> <html> <body> <form method="post" action="/img"> Select image to upload: <input type="file" name= ...

Switch between accordion items

Currently, I have a React Js accordion in which clicking on an item opens the panel. To close it, you need to click on another item. However, I am looking to enhance this functionality by allowing the active panel to be closed after clicking on the AccButt ...

The server returned a response that was void of any content

I have encountered an issue while trying to retrieve data from my server. The request works perfectly fine when tested with Postman, returning the expected data. However, upon implementing the request in my application, I receive an empty object with prope ...

Creating JSON data based on user provided input within a text area

I am currently developing an application that requires a json datafile to generate certain elements. I am looking to gather user input through this form: { "nodes": [ { "id": "n0", "label": "A node", "x": 0, "y": 0, "si ...

Initiate the Material TextField onChange event from within a nested component

I am currently working on a component that looks like this: class IncrementField extends Component { inputRef; changeValue() { this.inputRef.value = parseInt(this.inputRef.value) + 1; } render() { const { ...other } = this.props; return ( ...

Swapping out the document.createElement() method for React.createElement()

In a JavaScript library, I utilize document.createElement() to create an HTMLElement. Now, I am looking to develop a React library with the same functionality. My initial thought was to substitute document.createElement() with React.createElement(). There ...

Is there a way to deactivate a button upon clicking and then substitute it with a new button that serves a different purpose in AngularJS?

Is there a way to deactivate a button once clicked and substitute it with another button that performs a different task using AngularJS? Here is the button in question: <button type="submit" class="btn btn-small btn-default" ng-disabled="isteam==0 || ...

Searching for a value in an associative array using PHP

One puzzling issue I've encountered involves retrieving the key from an array by searching for its corresponding value. In this particular code snippet, it's perplexing that array_search() fails to locate the key when the file extension in the $u ...

Whenever I try to run npm start, my webpack is not able to locate my index.html page

Recently delving into the world of node.js and its packages, I initiated by executing npm init to lay out the package.json structure shown below: { "name": "test", "version": "1.0.0", "description": & ...

JavaScript hard-coded object functions as an argument, however it does not reference the global object

Recently, I encountered a strange issue while working with JQuery Flot. Initially, my code looked like this: var plot = null; function initPlot () { plot = $.plot("#graph", myData, { /* my options here */ }); } and everything was functioning correc ...

"Deactivate the escaping feature in PHP when using heredoc syntax

My PHP code generates minified JS output using the heredoc. Take a look at this snippet: function prerefresh(){$("#len").empty();predata.forEach(item)} I've highlighted that the {$ is causing issues with variable escaping in my heredoc. Is there a ...

What are some ways I can efficiently download large attachments without disrupting the user's experience?

I'm encountering some challenges with handling large attachments in my project. Initially, I had this link code: <a :download="scope.row.name" :href="`data:${scope.row.type};base64,${scope.row.contentBytes}`">download</a& ...

Vue.js computed property experiencing a minor setback

I'm currently working on developing a test-taking system using Vue and Laravel. When a user inputs the test code and email address, they are directed to the test page. To display all the test questions based on the entered code, I implemented a naviga ...

Activate AngularJS autocomplete when populating the input field using JavaScript

I'm currently facing an issue with updating the value of an input field on a website using JavaScript. Although I can successfully update the input field's value, I find that I am unable to trigger the autocomplete feature. Interestingly, when ...

Replacing child routes with an Angular wildcard route

I'm facing an issue with integrating a module named "host" into the app-routing.module. The problem I encountered is that the wildcard route takes precedence over loading the Host component, leading to the display of the PageNotFoundComponent instead. ...

What is the best way to obtain the parent of a recursive array structure?

Here is an example of an array structure: $navArray = array( array( 'id'=>1, 'text'=>'1A', 'href'=>'1a', 'childs'=>array( array( ...

Encountering an issue while attempting to implement Redux Toolkit alongside the MUI ToggleButtonGroup component

The error message initially started as: Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. When I attempted to update the Redux state using a dispatcher, the handleChange function suddenly showed an e ...