Retrieve corresponding values from a nested array in JavaScript

I'm struggling to extract specific cars from a list in Javascript.

Here is the list of cars:

const cars = [
  {
    id: 1,
    brand: "Mercedes Benz",
    properties: [
    {
      property: "Mechanical",
      value: 2,
    },
    {
      property: "Chemical",
      value: 2,
    },
    {
      property: "Pressure",
      value: 3,
    }],
  },
  
  {
    id: 2,
    brand: "BMW",
    properties: [
    {
      property: "Mechanical",
      value: 5,
    },
    {
      property: "Chemical",
      value: 3,
    },
    {
      property: "Pressure",
      value: 6,
    }],
  }
]

To achieve this, I am looking for cars that have a particular property with a value greater than X

For example, if I specify 'Mechanical' as the property and '3' as the value, I should get back the entire object with id 2

Does anyone have any suggestions? This has been quite challenging for me

Apologies for the formatting issues with the code, I'm having trouble posting it formatted on StackOverflow.

Tip: Try pasting it into a Node REPL ;)

Thank you in advance

Answer №1

Try using the filter method:

const targetFeature = "Mechanical";
const minThreshold = 3;

const relevantItems = items.filter(item =>
    item.attributes.some(
        attr => attr.attribute === targetFeature && attr.value >= minThreshold
    )
);

If you only need the first matching item instead of an array, switch out filter with find.

Answer №2

To filter out cars with properties greater than a specified value, you can define the propGreaterThan function. This function takes the desired property and the minimum value it should exceed as parameters. By utilizing the filter method on the array of cars and then using the find method on the properties array within each car object, you can identify the relevant cars.

const vehicles = [
  {
    id: 1,
    brand: "Audi",
    properties: [
    {
      property: "Weight",
      value: 3000,
    },
    {
      property: "Horsepower",
      value: 400,
    },
    {
      property: "Torque",
      value: 350,
    }],
  },
  
  {
    id: 2,
    brand: "Toyota",
    properties: [
    {
      property: "Weight",
      value: 2500,
    },
    {
      property: "Horsepower",
      value: 200,
    },
    {
      property: "Torque",
      value: 275,
    }],
  }
]

function propGreaterThan(prop, num) {
  return vehicles.filter(vehicle => {
    return vehicle.properties.find(p => p.property === prop).value > num;
  });
}

console.log(
  propGreaterThan("Horsepower", 250)
)

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

Ways to extract input values from a specific row in a textbox as users input data

On a button click, I am dynamically adding data to an HTML table using the loadbooks function. When the user clicks on the button, the table is populated with data. <button id="button" onclick="loadbooks()"></button> function loadbooks() { ... ...

How can you convert all nodes of a nested JSON tree into class instances in Angular 2 using Typescript?

I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows: JSON Response { "name":"animal", "state":false, "children":[ { "name" ...

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...

Divide a JSON dataset into two distinct JSON files and incorporate them within the code

My JSON file structure is as follows: { "rID": "1", "rFI": "01", "rTN": "0011", "rAN": "11", "sID&quo ...

Tooltipster fails to function with elements that are dynamically created

I've been struggling with this issue for several days now, but I can't seem to find a solution. In my JavaScript code, I have a function that generates HTML after an Ajax call is completed. I call this function in the following manner: $(documen ...

Plaid webhook failing to activate

I've been struggling to set up Plaid transaction webhooks in an api, as I can't seem to get any webhooks to trigger. I followed the plaid quickstart code and included the webhook parameter: Plaid.create({ apiVersion: "v2", clientName: ...

Don't pay attention to jquery.change

Consider the code snippet below: $(".someSelector").change(function() { // Do something // Call function // console.log('test') }); An issue arises where this code is triggered twice: once when focus is lo ...

Prevent any http requests until an observable completes its task

I'm currently developing an Angular interceptor where, before sending any non-GET requests, I need to make a GET request to obtain a specific header from the server and then set that header on all subsequent requests. Is there a method for achieving t ...

Utilize JavaScript to establish an object with key and value pairings

Wanting to loop through and create an object that contains key => [value], if the key already exists, simply add the value. Here is what I have tried so far: let dataName = []; let obj = {}; checkboxes.forEach(checkbox => { if (checkbox.che ...

Issues with $routeProvider in a web page hosted by Express.js

As I embark on creating my very first Express.js/Angular application, I'm encountering a challenge with the $routeProvider in the page served by the Express.js application. Let's take a look at the server.js: var express = require('express& ...

Arrays causing Typescript compilation errors

There are a pair of typescript documents: one file as a module that implements the Client class export class Client { the other file as the main document that imports the module and generates an array of clients import c = module("client ...

Strategies for managing asynchronous forEach loops, inserting outcomes into a database, and displaying the finalized dataset

I want to achieve the following steps: Call an API resource Receive an array of records - [arr] Iterate over [arr] and execute a function which involves making another async call to an API for each item Create an object for each iteration that includes el ...

Determine the mean values to showcase at the center of a D3 donut graph

Check out this plunkr where I'm utilizing angularjs and d3.js. In the plunkr, I've created several donut charts. I'm interested in learning how to display the average data in the center of the arc instead of the percentage. Additionally, I& ...

You can eliminate the display flex property from the MuiCollapse-wrapper

Having trouble removing the display flex property from the MuiCollapse-wrapper, I did some research and found the rule name for the wrapper in this link https://material-ui.com/api/collapse/ I have been unsuccessful in overwriting the class name wrapper t ...

Issue with Angular: boolean value remains unchanged

Currently, I'm encountering an issue with my application. My objective is to establish a list containing checkboxes that toggle their values between true and false when clicked. Sounds simple enough, right? Below is the HTML code snippet: <l ...

Unlocking the potential of the ‘Rx Observable’ in Angular 2 to effectively tackle double click issues

let button = document.querySelector('.mbtn'); let lab = document.querySelector('.mlab'); let clickStream = Observable.fromEvent(button,'click'); let doubleClickStream = clickStream .buffer(()=> clickStream.thrott ...

Automate scrolling to the rightmost column in a table

What is the best way to navigate to the last column in a table with horizontal scrolling without directly targeting the last column? For example, instead of using: document.getElementsByClassName('makeStyles-tableCell-251')[document.getElements ...

What are the steps to implementing the jQuery live() function in this particular code?

I am seeking assistance in applying the live() function to this particular code. The following code will be dynamically inserted using JavaScript: <a class="link" href="url"><span>This content is hidden</span></a> This is the Jav ...

Deactivate tag Script using JQuery

Is there a way to dynamically remove two <script> tags from a page at the document ready event? Each tag is assigned its own unique id. I attempted to use the following code: $("#idPrimoScript").remove(); $("#idSecondoScript").remove(); However, t ...

What could be causing the server to return an empty response to an ajax HTTP POST request?

Attempting to make a POST request using ajax in the following manner: $.ajax({ type: "POST", url: 'http://192.168.1.140/', data: "{}", dataType: "json", ...