Guide on searching in a multidimensional array with VueJS or JavaScript

Recently, I started embarking on a project using Vue JS and as a newbie to the framework, I came across a certain dilemma. How can I retrieve all data with an id of 1 when I input a specific value? Below is an illustration of my data structure:

 {
    'A': [{
        1: [{
            id: 1, 
            name: 'John'
        }],
        2: [{
            id: 5,
            name: 'Ken'
        }]
    }],
    'B': [{
        1: {
            id: 1,
            name: 'Leena'
        }
    }],
    'C': [{
        1: [{
            id: 1,
            name: 'Jesica'
        }],
        2: [{
            id: 18,
            name: 'Mike'
        }]
    }]
}

The desired outcome should resemble the following, given that they share the same id value:

{
    'A': [{
        1: [{
            id: 1, 
            name: 'John'
        }]
    }],
    'B': [{
        1: {
            id: 1,
            name: 'Leena'
        }
    }],
    'C': [{
        1: [{
            id: 1,
            name: 'Jesica'
        }]
    }]
}

Answer №1

If you are in control of the data structure format, consider changing it to something more manageable. One approach is to assign each capital letter property an array of objects:

let dataset = { 
  'A': [{id: 1, name: 'John'}, {id: 2, name: 'Sally'}],
  'B': [{id: 1, name: 'Bob'}],
  ...
}

An even better option would be to structure the data as an array of objects with a capital letter designated as the group property value and the id-name pairs as people property values (or any other logical designation):

let dataset = [{
    group: 'A', people: [{id: 1, name: 'John'}, {id: 2, name: 'Sally'}],
  }, {
    group: 'B', people: [{id: 1, name: 'Bob'}],
  }, {
    ...
}]

With this setup, filtering data by a specific id becomes quite straightforward:

function filterObject(foo, id) {
  return foo.map(i => i.people.filter(j => j.id == id));
}

You can view a working example here.


If you must work with the complex data structure provided, here is a function that can help achieve your goals:

let filterObject = function(foo, id) {
  let bar = {};

  Object.keys(foo).map((key) => {
    for (let i = 0; i < foo[key].length; i++) {
      Object.keys(foo[key][i]).map((index) => {
        for (let j = 0; j < foo[key][i][index].length; j++) {
          if (foo[key][i][index][j].id != id) {
            continue;
          }

          if (!bar[key]) {
            bar[key] = [];
          }
          if (!bar[key][i]) {
            bar[key][i] = {};
          }
          if (!bar[key][i][index]) {
            bar[key][i][index] = [];
          }

          bar[key][i][index][j] = foo[key][i][index][j];
        }
      })
    }
  });

  return bar
}

Explore a functional demo here.

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

Using a button to wrap a router-link element in Vue.js

Is it possible to nest a router-link inside a button tag? My goal is to trigger the routing action to the intended page when the button is clicked. ...

What sets apart an exception from a promise left unfulfilled?

As I delve into the topic of error handling, I came across an interesting concept in my reading material. The literature explains that if a throw statement occurs within a Promise's catch function, it is considered a rejection. It draws a distinctio ...

Creating Vue components based on a deeply nested data structure

Is there a way to efficiently utilize a nested object for generating Vue components? My nested object structure is as follows: "api": { "v1": { "groups": { "create": true, "get": true, ...

What is causing the lack of rendering in a React component after modifying the state?

Let me show you the compressed version of my code for a quick look const PropertiesList: FC = (estatesObject) => { const [estates, setEstates] = useState(Object.values(estatesObject)) const filterEstatesUp = () => { // sorting an arr ...

What is the best way to determine the size of a char array?

Here is a code snippet written in Java. for (int j = 0; j < charArray[i].length; j++) { System.out.print(charArray[i][j]); } I have a simple question: How can I achieve the same functionality as the Java length property but in C++? ...

Beginner Attempting to Create a JavaScript Age Calculator

As a beginner in self-learning, I've recently started diving into the world of JavaScript. Currently, I am facing a challenge with an assignment from an online code camp that I just can't seem to figure out. Despite grasping the basics, I struggl ...

Manipulating the content of an array based on a specific key value using JavaScript's

Looking for a way to utilize a multidimensional array fruits in my code. The goal is to splice and push the values from the suggestFruits array into either the red or green fruits array based on the type specified. For example, items with type:1 should go ...

Exploring the use of the "++" operator in Regular

Is there a way to detect the presence of ++, --, // or ** signs in a string? Any help would be greatly appreciated. var str = document.getElementById('screen').innerHTML; var res = str.substring(0, str.length); var patt1 = ++,--,//,**; var resul ...

The animation of a disappearing div with CSS is not stopping when hovering over it

Hello, I've been working on a snackbar feature that appears and disappears on a set timer but also needs to pause when hovered over. Unfortunately, the current setup with setTimeout and useState is causing issues with this functionality. I have looke ...

Is it necessary for a TypeScript Library's repository to include the JavaScript version?

Is it necessary to include a JavaScript version of the library along with the Typescript repository for consumers? Or is it best to let consumers handle the compilation process themselves? Or should I consider another approach altogether? ...

Find the location in a node.js script where a promise was rejected

Recently, I encountered a code snippet from an npm package that has been causing me some trouble. The issue is that I'm having difficulty in pinpointing where the rejected promise is being created or rejected within node.js. const someHiddenEvil = fu ...

The JQuery ajax post function is typically called towards the conclusion of a JavaScript script

I am struggling with validating whether a username is already taken. I have been attempting to determine if the username exists by utilizing the "post" method in jQuery. However, every time I execute this function, the script seems to skip to the end of th ...

Combining arrays with identical values into a new array?

I have a large array with multiple similar values, but I want to group all arrays with the same value into another array. Here's an example of the array: array(4) { [0]=> array(8) { ["symbol"]=> string(3) "aaaa" ["name"]=> ...

Guide to keeping numerous movie titles in an array with a for loop in Java

I am currently working on a project for my school assignment, where I need to collect multiple movie titles along with the number of copies of each movie and store them in an array. However, every time I enter a new title, it replaces the previous one(s). ...

Having trouble getting images to display in Vue markdown?

I am currently utilizing the vue-markdown package for rendering markdown content. The package works fine except for images, which do not display as expected. Interestingly, when using an img element with the correct file path, the image shows up without an ...

Are There Any Techniques for Adding Objects to an Array in a Unique Way?

Is there a simple way to add an object to an array in ES6 while ensuring it is unique? For example: MyArray.pushUniquely(x); Or is it better to stick with the older method like this? : MyMethod(x) { if ( MyArray.IndexOf(x) === -1 ) MyArra ...

Looking for assistance with resizing and repositioning an image within a viewport?

The JSFiddle code can be found at this link - https://jsfiddle.net/pmi2018/smewua0k/211/ Javascript $('#rotate').click(function(e) { updateImage(90, 0) console.log("rotation"); }); $('#zoom-in').click(function() { updateImage(0 ...

Using Chance JS library in Vue.js

I'm facing a dilemma with my database entry views - one for songs and the other for genres. While trying to automatically fill input fields with random data, I noticed an issue when importing chance. It seems that importing chance in the genres file b ...

JavaScript first, middle, and last names

When working with Javascript, I have encountered a challenge. I am attempting to extract the First, Middle, and Last names from a full name input into three separate fields - Character Length, Middle Name, and Initials. At this point, I have successfull ...

When the user clicks on a specific element, ensure that it is the main focus and generate an overlay

One of my challenges is implementing a custom element that captures user input upon clicking, focusing on it and overlaying other elements. I want the overlay to disappear if the user clicks outside the div. I attempted to achieve this using the iron-over ...