Using Javascript to search through nested arrays for specific elements

What is the best way to filter an inner array of objects by key value when given an array with objects that contain options?

Consider the scenario below:

let test = [{
  "options": [{
     "label": "Audi",
     "value": 10
   },
    {
     "label": "BMW",
     "value": 18
   },
   {
     "label": "Mercedes Benz",
     "value": 116
   },
   {
     "label": "VW",
     "value": 184
   }
 ],
 "label": "test1"
},
{
 "options": [{
    "label": "Adler",
    "value": 3664
  },
  {
    "label": "Alfa Romeo",
    "value": 3
  },
  {
    "label": "Alpine",
    "value": 4
  }
],
 "label": "test2"
}
]

If we want to extract and return the object:

 {
   "label": "Audi",
   "value": 10
 }

based on a filter for keyword Audi,

return label.toLowerCase().includes(inputValue.toLowerCase());

the code snippet I attempted used a map function like so:

test.map((k) => {
              res = k.options.filter((j) => {
                inputValue.toLowerCase();
                if (j.label.toLowerCase().includes(inputValue.toLowerCase())) {
                  return j;
                }
              });
            });

Answer №1

Ensure that you are returning the result of filter() instead of just assigning it to a variable. This way, map() will be able to return the desired results.

let sample = [{
    "items": [{
        "name": "Toyota",
        "quantity": 10
      },
      {
        "name": "Honda",
        "quantity": 18
      },
      {
        "name": "Nissan",
        "quantity": 116
      },
      {
        "name": "Ford",
        "quantity": 184
      }
    ],
    "category": "cars"
  },
  {
    "items": [{
        "name": "Apple",
        "quantity": 3664
      },
      {
        "name": "Banana",
        "quantity": 3
      },
      {
        "name": "Orange",
        "quantity": 4
      }
    ],
    "category": "fruits"
  }
]
let searchValue = "toyota";
let searchTerm = searchValue.toLowerCase();
let output = sample.map(item => item.items.filter(i => i.name.toLowerCase().includes(searchTerm)));
console.log(output);

Answer №2

Use this code snippet to retrieve all options that match the given search query :

function filterOptionsByQuery(array, query) {
  return array.reduce((prev, current) => prev.concat(current.options), []).filter(item => item.label.includes(query))
}

filterOptionsByQuery(test, 'Audi')

Answer №3

Combine flatMap() with filter():

let vehicles=[{options:[{label:"Audi",value:10},{label:"BMW",value:18},{label:"Mercedes Benz",value:116},{label:"VW",value:184}],label:"test1"},{options:[{label:"Adler",value:3664},{label:"Alfa Romeo",value:3},{label:"Alpine",value:4}],label:"test2"}]

let result = vehicles.flatMap(vehicle => {
    return vehicle.options.filter(car => car.label == "Audi")
})[0]

console.log(result)

Answer №4

Make sure to traverse your array two levels deep for optimal results.

function filterArray(needle, haystack) {
  return haystack
    .map(h => h.options)
    .flatMap(h => h )
    .filter(h => h.label.toLowerCase().includes(needle.toLowerCase()));

Check out the example on CodeSandbox

Answer №5

Here is a snippet that could provide the solution:

print(test[0].options[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

Steps to create a TypeScript function that mimics a JavaScript function

As I look at this javascript code: // find the user User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.json({ success: false, message: 'Authentication failed. User not found.' ...

Connect the AngularJS data model with a Foundation checkbox element

I am attempting to link a model (a boolean value) to a checkbox created with Foundation (Zurb). I have created a small demonstration displaying the issue: http://jsfiddle.net/JmZes/53/ One approach could involve simply creating a function that triggers o ...

Using Javascript to extract formatted text from a webpage and save it to the clipboard

I've developed a straightforward tool for employees to customize their company email signature. The tool generates text with specific styling, including bold fonts and a touch of color - nothing too extravagant. When I manually copy and paste the styl ...

The 'log' property cannot be found on the type '{ new (): Console; prototype: Console; }' - error code TS2339

class welcome { constructor(public msg: string){} } var greeting = new welcome('hello Vishal'); Console.log(greeting.msg); I encountered an error at the Console.log statement. The details of the error can be seen in the image attached below. ...

Discover a non-null string within a deeply nested data structure

Within the 'task' object, the value of the 'door' property can vary each time it is accessed: var task = {}; task["123"] = [{"door":""}, {"door":""}, {"door":""}, {"door":""}]; task["456"] = [{"door":""}, {"door":"close"}, {"door":"" ...

What is the best way to determine the accurate size of a div's content?

There are 2 blocks, and the first one has a click handler that assigns the block's scrollWidth to its width property. There is no padding or borders, but when the property is assigned, one word wraps to the next line. The issue seems to be that scrol ...

What is the best way to halt animations for all scenes except for the one currently being displayed?

I have a program with multiple scenes, but only one scene will be visible at a time. How can I stop the animation for all other scenes except the current one to improve performance? Each scene has many objects that are straining the performance. I believe ...

Cordova experiencing difficulty loading platform API

Lately, I've been facing a persistent issue with Cordova. Whenever I try to run it in the browser, an error pops up saying that the browser is not added as a platform. Even when I attempt to add the browser as a platform, another error occurs stating ...

Troubleshooting a Safari bug with element.click()

When the 'subButton2' button is clicked, the 'uploadBtn'(display:none;) should also be clicked. This functionality needs to work across different browsers: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_html_click The cod ...

What is the best way to organize the elements of an array into three separate columns?

I am in need of a specific output.. 1 3 5 2 4 6 I wish to utilize an array function such as array(1,2,3,4,5,6). If I were to modify this array to array(1,2,3), then the output should appear as follows: 1 2 3 The rule is to have a maximum of 3 columns. ...

Tips for adjusting a pre-filled form?

When a form is rendered by onClick from a component, it loads with values. I want to be able to edit these current values and then perform an update operation. Here is the link to the sandbox: https://codesandbox.io/s/material-demo-forked-e9fju?file=/demo ...

Is there a more efficient method for managing Express rendering based on whether the request is an AJAX post or an HTML form submission?

Currently, I am working on an HTML form and incorporating jQuery's AJAX post feature to retrieve information based on the success or failure of a database insertion. Within my code, I have set the ajax post variable to true when utilizing AJAX postin ...

Creating a simulation of browser cookies using Javascript

I've embarked on a mission to develop a comprehensive web proxy using node.js that downloads webpages and directly showcases them to the client. The implementation of cookies has proven to be trickier than expected, given their myriad rules and comple ...

How did my attempt to add a length() method to Object end up breaking jQuery?

Here is the code I created: Object.prototype.length = function(){ var count = -1; for(var i in this) count++; return count; } Surprisingly, when viewing my page with Firebug enabled, it gives an error stating that jQuery's .appendTo() is ...

Finding the count of childNodes within a div using Selenium

I've been grappling with this issue for the majority of today; I'm trying to tally up the number of childNodes within a parent div. It's essentially mimicking a list where each childNode represents a row that I want to count. The HTML struct ...

An error was encountered in the JSON syntax: Unexpected symbol <

I have encountered a problem with my code that I cannot seem to resolve. Despite the JSON data being successfully sent to the backend and processed correctly, the success function of the call is never triggered. Here is the snippet of my function: Regist ...

Disappear gradually within the click event function

I have a coding dilemma that I can't seem to solve. My code displays a question when clicked and also shows the answer for a set period of time. Everything works perfectly fine without the fadeOut function in the code. However, as soon as I add the fa ...

Is it possible to utilize Dictionaries (key, value) collections with JQuery?

Is jQuery capable of supporting a collection of Dictionaries which consists of keys and values? I am interested in organizing the following data into a structured format: [1, false] [2, true] [3, false] This structure should allow for adding, looking up ...

What is the best way to intentionally make a Node unit test fail when catching a Promise rejection?

When conducting unit tests with Node.js, I encountered a scenario where I needed to intentionally fail a test within a promise's catch block: doSomething() .then(...) .catch(ex => { // I need this test to fail at this point }); ...

Utilizing Regular Expressions and the Quill JS library to highlight a list of prohibited words in bold font?

I'm currently working on developing a straightforward webpage where the text submitted to the server is scanned against a list of prohibited words. If any forbidden words are detected, they should be highlighted in bold. Due to formatting restrictions ...