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

How can I retrieve the Sequelize results in the form of a 2D array rather than an array of objects?

I have a situation where I am using the Sequelize query() method like this: const sequelize = new Sequelize(...); ... // IMPORTANT: Cannot modify this query const queryFromUser = "SELECT table1.colname, table2.colname FROM table1 JOIN table2 ON/*...*/ ...

What is the best way to replicate a synchronous ajax call? (mimicking synchronous behavior with asynchronous methods)

Given that a "native" synchronous ajax call can block the user interface of the browser, it may not be suitable for many real-world scenarios (including mine). I am curious to know if there is a way to mimic a synchronous (blocking) ajax call using an asy ...

Leveraging the power of jQuery and vanilla JavaScript to create a pop-up print window for a Div element within a CMS platform that does not support media query stylesheets

I have been grappling with this particular issue for weeks now, seeking guidance from previous inquiries here. Yet, despite the helpful hints, I am still struggling to find a viable solution. My website features a scrolling sidebar measuring approximately ...

Guide: Building Angular/Bootstrap button checkboxes within a loop

I am in the process of designing a grid (table with ng-repeat) in which each row contains 4 columns of buttons. My goal is to use checkboxes as the buttons, like the Angular/Bootstrap btn-checkbox, so that they can be toggled on and off. I plan to set thei ...

Altering the backdrop upon hovering over an element

As a beginner in Javascript and Jquery, I am working on creating an interactive feature where hovering over one element changes the background image in another column. I have managed to write the function, but now I want to add an animation to the image tr ...

The integration of <form> with jQuery Ajax error

I have come across this HTML form function FormSubmit (){ $.ajax({ url:'dotar.php', type:'post', data:$('form').serialize(), success:function(){ setTi ...

Challenges with ReactToPrint Library and Optimizing Layout for Thermal Printer

Working on a React.js project, I have been using the ReactToPrint library to print a specific section of my page. However, I am facing an issue where the page size remains too large and important content is being left out in the printed receipt. It seems ...

React - Incorporating Axios catch errors directly within form components

When a user registers, my backend checks if the email and/or username provided are already in use by another user. The response from Axios catch error is logged into the web console. I want to associate each email and username with their respective fields ...

Utilizing variable values in HTML and CSS to enhance a website's functionality

My current project involves modifying an HTML web resource for use in Dynamics 365. I need to replace a static URL with a dynamic value obtained via Javascript, specifically: var URL = Xrm.Page.context.getClientUrl(); There are multiple instances within ...

After submitting my form, the Bootstrap Modal does not hide as intended by my Ajax

I am facing an issue with my webpage that displays 6 Bootstrap Cards in 3 columns. Each card contains an image, name, description, and a footer button. When a user clicks on the button, a Bootstrap Modal opens with specific data fetched from a SQL row by I ...

The sequence of data and the final event triggered by http.createServer

const server = http.createServer(async (request, response) => { if (request.method === "POST") { var data = ""; request .on("data", async (chunk) => { console.log("1"); data + ...

Struggling to make cookies stick in IE9

Here is the code snippet I am currently using: <script> var time = new Date(); time.setFullYear(time.getFullYear() + 1, time.getMonth(), time.getDay()); expires = ";expires=" + time.toGMTString(); document.write(expires); doc ...

Submitting Multi-part forms using JQuery/Ajax and Spring Rest API

Recently, I started exploring JQuery and decided to experiment with asynchronous multipart form uploading. The form includes various data fields along with a file type. On the server side (using Spring), I have set up the code as follows: @RequestMapping ...

Revamp the Twitter button parameters or alter its settings

I'm working on a web page that includes a Twitter button. Before the button, there is an input field and a form where users can easily add relevant hashtags for the page. The goal is to take the text from the input field and populate it in the Twitter ...

Discover siblings in React component siblings

Creating a parent element (Board) that generates a list of children and provides a method to access this list can be done like so: export default class Board extends React.Component { constructor(props) { super(props); this.getList = t ...

Timing issues with setInterval and setTimeout are causing them to execute at the incorrect moments

I am struggling with changing the background image using setInterval and setTimeout every x seconds. The issue I am facing is that the timer is not working as intended, causing images to change instantly instead. let images = ['background1.jpg&apo ...

collapse each <b-collapse> when a button is clicked (initially shown)

I am facing an issue with a series of connected b-buttons and b-collapse, all initially set to be visible (open). My goal is to hide them all when a toggle from my parent.vue component is activated - so upon clicking a button in the parent component, I wa ...

The useEffect hook in ReactJs is triggering multiple times

Encountering challenges while developing an Infinite scroll using ReactJs and Intersection observer API. Upon initial application load, the API gets called twice instead of once. This behavior may be due to strict mode, although not confirmed. Additionall ...

Please optimize this method to decrease its Cognitive Complexity from 21 to the maximum allowed limit of 15. What are some strategies for refactoring and simplifying the

How can I simplify this code to reduce its complexity? Sonarqube is flagging the error---> Refactor this method to reduce its Cognitive Complexity from 21 to the allowed 15. this.deviceDetails = this.data && {...this.data.deviceInfo} || {}; if (th ...

Creating a login page with Titanium Appelerator is a breeze

Looking for guidance on creating a login page using Titanium Appcelerator docs. Struggling to grasp the documentation - any recommendations for tutorials on storing user data in a database, accessing it, and implementing a login system? ...