Is there a way to search for a specific item within a nested array?

I have 2 arrays within an array, each containing objects. How can I locate the object with the name "Sneijder"?

const players = [
  [
    {
      id: 1,
      name: "Hagi",
    },
    {
      id: 2,
      name: "Carlos",
    },
  ],
  [
    {
      id: 3,
      name: "Zidane",
    },
    {
      id: 4,
      name: "Sneijder",
    },
  ],
];

Answer №1

To simplify the array, use the flat method followed by the find function to locate your desired item within the flattened array:

const players = [
    [
        {
            id: 1,
            name: "Ronaldo",
        },
        {
            id: 2,
            name: "Messi",
        },
    ],
    [
        {
            id: 3,
            name: "Neymar",
        },
        {
            id: 4,
            name: "Mbappe",
        },
    ],
];

const player = players.flat().find((p) => p.name === "Mbappe")
console.log(player)

Answer №2

Any of the 3 combinations can be utilized or a different one altogether. The outcome will remain consistent, although the complexity may vary when dealing with other instances where the desired object is positioned at the beginning or in the middle.

const players = [
  [{
      id: 1,
      name: "Ronaldo",
    },
    {
      id: 2,
      name: "Messi",
    },
  ],
  [{
      id: 3,
      name: "Neymar",
    },
    {
      id: 4,
      name: "Mbappe",
    },
   ],
];

let player = "";
players.forEach(x => player = x.find(y => y.name === "Mbappe"));
console.log("Approach 1", player);
player = players.flat().find(y => y.name === "Mbappe");
console.log("Approach 2", player);
players.some(x => {
  const [x1, x2] = x;
  if (x1.name === "Mbappe") return player = x1;
  if (x2.name === "Mbappe") return player = x2;
});
console.log("Approach 3", player);

Answer №3

If you want to combine arrays and then search for a specific item by name, consider using Array.prototype.concat method.

const sneijderObj = [].concat.apply([], players).find(x => x.name === 'Sneijder');
console.log(sneijderObj);

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

User update function is not being triggered by Ionic 2 Express call

I am currently working on implementing a feature in my Ionic 2 program that updates a user field when triggered. The code snippet below is from my user-service.ts file: // Update a user update(user: User): Observable<User> { let url = `${this.u ...

Why is there nothing showing up on the screen?

Just diving into Three.js and might've messed up somewhere. I'm trying to generate a geometry by using coordinates and surface data from a .k file. I checked the geometry.vertices and geometry.faces, they seem fine. I even played around with the ...

The POST request functions flawlessly on the local server, but encounters issues once deployed to Google Cloud Platform

Even though the Axios post request works fine on my local server, it throws a 404 not found error after I deploy the project on Google Cloud. On localhost, all requests are directed to URLs starting with http://localhost:9000/api/..., handling post reques ...

The success of your order hinges on jQuery being defined when using browserify

I encountered an issue while attempting to utilize a plugin located in /js/lib/stellar.jquery.js: var $ = require('jquery'); require('./lib/stellar.jquery') $(function(){ $.stellar(); }); Upon running the code, I received an err ...

Experimenting with the inner workings of a method by utilizing vue-test-utils alongside Jest

Is there a way to properly test the internal logic of this method? For instance: async method () { this.isLoading = true; await this.GET_OFFERS(); this.isLoading = false; this.router.push("/somewhere"); } This method toggles isLoading, ...

Python is experiencing difficulties with copying xpath elements

I attempted to utilize some Python code to access Twitter and retrieve the "Happening now" text. Unfortunately, it was unsuccessful. import webbrowser print("Visiting Twitter.com...") webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/c ...

Material-UI - Switching thumb styles in a range slider

Looking for a way to style two entities differently on the Material-UI Slider? Entity A as a white circle and Entity B as a red circle? While using data-index can work, there's a flaw when sliding. Is there a better approach? if (data-index === 0) { ...

Ways to verify the presence of an element in a list

I found this interesting JS code snippet: ;(function ($) { $('.filter-opts .opt').click(function(){ var selectedName = $(this).html(); $('.append').append('<li>' + selectedName + '</li> ...

Sending numerous messages from a single event using Socket.io

After an exhaustive search, I have yet to find a solution to my problem. I am attempting to send a message from the server every time it detects a file change in a specific directory. However, instead of sending just one message, it sends the same message ...

ESLint version 8.0.0 encountered an error while attempting to fetch the '@typescript-eslint' plugin

Hey there, I'm in need of some assistance. I encountered an error while trying to build a project. Uh-oh! Something didn't go as planned! :( ESLint: 8.0.0 TypeError: Failed to load plugin '@typescript-eslint' specified in ' ...

Having trouble grasping the functionality of Javascript in this code (using Coffeescript and Commander in Node.js)

I'm facing some issues when using Commander in Node.js - the parseInt function doesn't seem to be working correctly in my code: commander = require 'commander' #parseInt = (str) => parseInt str #I attempted to add this line witho ...

Error: The function res.json is not recognized. Despite searching through related inquiries, I cannot find a solution to my specific issue

Struggling to find a solution and avoiding repetitive questions, I am facing an issue with my bug tracker. After submitting the form and sending it to the server side, the bug is created in the database. However, when I save the bug using await bug.save() ...

Currently, I am working on a project and encountering an issue with html2canvas

const handleDownloadImage = async () => { try { const canvas = await html2canvas(cardRef.current); console.log(cardRef.current); const imageData = canvas.toDataURL("image/png"); setImageUrl(imageData); } catch ( ...

Issue encountered when displaying various data options in the dropdown menus within a modal window

My goal is to display a modal when a button is clicked. The modal renders perfectly fine, but I am facing an issue with duplication of dropdowns inside the modal when the "add more" button is clicked. The main issues are: 1. Selecting the first option in ...

Design a progress bar that advances in increments of at least two and up to a maximum of

My task involves managing a simple list. const [progressBar, setProgressBar] = useState([ { isActive: false, name: "step1" }, { isActive: false, name: "step2" }, { isActive: false, name: "step3" }, { isActive ...

AngularJS Error: $element.find(...) does not support iteration

I'm attempting to utilize a datatable in my AngularJS application. Below is the HTML code I've implemented: <div ng-app="datatable"> <div ng-controller="voucherlistcontroller"> ...

What is the best way to incorporate a function within a $.click (jquery) event that utilizes an id directly from the clicked element?

It seems that my title may not be very clear, but I have a jQuery code snippet that is causing some issues. The problem stems from the fact that when I click on an image with the class 'slideimg', I expect a function named slideDo to be executed, ...

Encountering issue with accessing req.body within Next.js 13 middleware function

The issue I am facing in the code snippet below is related to validating the request body against a schema from zod. The current situation leads to failure and catches errors because req.body returns a ReadableStream<Uint8Array> instead of the expect ...

Guide on how to retrieve a value using image.onload on the client side

I have encountered an issue with exporting a png image from an svg element using Blob. The problem arises when clicking the anchor tag to export the image, as the content is not rendered due to the asynchronous method (image.onload()) being called after th ...

What steps can I take to address the problem of my undefined .length value?

I encountered a length error while executing line 2 in this code snippet. index.js:10 Uncaught TypeError: Cannot read property 'length' of undefined" Sample Code: <div class="formCustomerName"> <label>Name:</label> ...