Refine JSON arrays by applying combined nested array filters

Currently, I am in the process of developing a JavaScript code that aims to filter JSON data based on a specific condition. Yesterday, I had posted a question seeking guidance on this matter How to filter data from a json response. However, since I had not made any attempts prior to posting the question, it received downvotes which I completely understand.

I experimented with using the 'filter' method, but encountered an issue where I ended up with an array within another array, leaving me stuck at that point. Below is the snippet of my code:

var arr2 = [
  [{
    "max": "0.685",
    "target_state": "6",
    "ingredients": "a",
    "rule_no": "7",
    "id": "18"
  }, {
    "max": "14",
    "target_state": "6",
    "ingredients": "b",
    "rule_no": "7",
    "id": "17"
  }],
  [{
    "max": "14",
    "target_state": "7",
    "ingredients": "b",
    "rule_no": "8",
    "id": "19"
  }, {
    "max": "1.36",
    "target_state": "7",
    "ingredients": "a",
    "rule_no": "8",
    "id": "20"
  }]
];

var result = arr2.reduce(function(a, b) {
    return a.concat(b);
  })
  .filter(function(obj) {
    return (obj.max == 0.685 && obj.ingredients === "a")
  });

alert(JSON.stringify(result[0].target_state));

When executing this code, it provides the output as "6". Although, my desired condition involves checking for multiple scenarios such as

((obj.max == 0.685 && obj.ingredients === "a") && (obj.max == 14 && obj.ingredients === "b"))
, sadly it does not return anything.

The expected outcome here should be "6".

You can view a working fiddle demonstrating this scenario: https://jsfiddle.net/vjt45xv4/14/

Please provide your insights on where I might be going wrong and how could I go about rectifying this problem.

Thank you!

Answer №1

It appears that I grasp your intention with this code snippet.

Why not give this alternative solution a try? It did the trick for me.

var result = arr2
  .filter(function(objects) {
    return ((objects.find((obj) => obj.ingredients === "a" ).max == 0.685) 
&& (objects.find((obj) => obj.ingredients === "b" ).max == 14));
  })
  .reduce(function(a, b) {
    return a.concat(b);
  });

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

ESLint only lints certain errors in the command-line interface

Incorporating eslint into my project has been a game-changer. Here's how my .eslintrc file is set up: // http://eslint.org/docs/rules { "parser": "babel-eslint", "env": { "browser": true, "node": true, "mocha": true }, "plugins": ...

Tips for toggling password visibility by clicking outside a password field

As I work on creating a password field that allows users to toggle the visibility of their password by clicking an eye icon, I am facing a challenge. I want the password to be hidden automatically when the user clicks outside the field, which requires a co ...

Showing or hiding child content based on the selected state of a radio button

This is a follow-up question from a previous one on changing check boxes to radio buttons. Now, I need to display child radio buttons and change the background color when the parent radio button is active. The child radio buttons should be hidden and the b ...

There seems to be an issue with the vue-cli when attempting to build in

Within my project files, there is a .env file present -public -src -.env.development.local In the package.json file, it contains: { "name": "my-website", "version": "0.1.0", "scripts": { ...

How can a Vue component interact with a JavaScript method?

Within my main.js file, I have configured Vue as follows: window.Vue = require('vue'); Vue.component('my-component', require('./components/MyComponent.vue')); const app = new Vue({ el: '#app', }); Additionall ...

Display the Ionic loading spinner until the data is fully loaded

Currently, I am developing an application using the Ionic framework. My goal is to display a loading spinner until all the data is retrieved from an API. In the Controller.js file: .controller('PrayersCtrl', function($scope, Prayers, $ionicLoad ...

What is the best way to add style to the title attribute of a dropdown menu item?

In my webform project, I have implemented a dropdown menu with custom tooltips for the list items. These tooltips are different from the display field and value field, which can be considered as the third column. To bind the tooltips to the list items usin ...

Retrieve the body's coordinates when dragging an element using the jQuery UI library

How can I obtain the coordinates of a dragged div upon drag and drop action, including left, right, and top positions? Additionally, how do I then use Ajax to post these coordinates? An example link can be found at jsfiddle.net/qPw92 <html> &l ...

Bower consistently installs the most up-to-date version instead of the version that was explicitly specified

Despite the version specified in the "bower.json" file, bower (v1.8.0) doesn't adhere to it and instead downloads the most recent version of the library available. It seems like it's not taking the version into account at all. Even downgrading to ...

I am having trouble getting my JavaScript to load

I've hit a roadblock trying to understand why my JavaScript code isn't executing properly. Could someone kindly point out what I may have overlooked? :( JSFiddle Link HTML Snippet <div class="po-markup"> <br> <a href="# ...

What is the best way to update a React state with JSON data?

Currently, I am dealing with a React component that sends a post request to an Express server hosted by myself. The server employs web3 for signing transactions on the Ethereum blockchain. Upon successful inclusion of the transaction in a block, a JSON obj ...

Working with AngularJS: Implementing a Service in a Controller

A service has been developed in AngularJS, but it is not being utilized in the controller. Service.js var appService = angular.module("appService", []); appService.service("bddService", function() { var bdds = bdd; this.getBdds = function(){ ...

Exploring the world of MVC4: Enhancing user experience with client-side

Solution: The answer provided by @www.innovacall.com is correct, I initially misunderstood it but now it works perfectly. Thank you for the help. Initial issue: I have been struggling with finding a solution to my problem. In my project, there is a mod ...

Issue with Three.js: Values in Uniforms not being updated

I'm currently working on animating the uniforms value of a shader using Tween.js when a button is clicked. The code snippet below shows my implementation: Shader.uniforms.threshold.needsUpdate = true; function fadeIn() { new TWEEN.Tween( Shader.un ...

What are some tips for streamlining a jq command?

I am currently working with a file called test.json that contains some data related to Kudu services. "items" : [ { "name" : "kudu-KUDU_TSERVER-2d63fec551a74320fdcc0c65007c76e4", "type" : "KUDU_TSERVER ...

A guide on retrieving a key from a JSON object in Ruby after using the to_json

I am encountering an error message that I need to parse as a JSON object in order to extract a key value pair from it. The message appears as follows {"message":"my message","error_code":404} The code snippet is as follows: r ...

Having difficulty retrieving the value of a variable obtained from the Google Distance Matrix function

Utilizing the Google distance matrix API to calculate the distance between two locations, I encountered an issue with global variable access. Despite changing the variable within a function, I found that I was unable to retrieve the updated value of the va ...

Is it necessary for JavaScript functions to be stored in a separate file in order to be invoked?

Here is the scenario that unfolded: Within a .php file, I had the following form: <form action="/flash_card/scripts/create_user_gate.php" onsubmit="return validateForm()" method="post"> <table align="center"> ...

How is it possible to encounter a Javascript unexpected token ] error within an HTML code?

While working on my project, I encountered a JavaScript error in the console of Chrome. The error message stated "Unexpected token ]" and it was pointing to a specific line of raw HTML code. I am puzzled about what could be causing this issue. Unfortunatel ...

Using $gte and $lte with number integers is causing an issue in mongodb

I need help retrieving documents that have at least one entry of 'cov.res.timestamp' within a specific range. {'cov.res.timestamp': { $gte: 1571424600, $lte: 1571597580 }} Currently, it seems to be listing docum ...