Tips for choosing and filtering the preferred object in ES6

Consider this array structure:

const testData = [
{
  group: "Team1",
  info: [
    {
      key: 123,
      person: "Alice",
      type: "Football"
    },
    {
      key: 456,
      person: "Bob",
      type: "Tennis"
    },]
  },
  {
   group: "Team2",
  info: [
    {
      key: 890,
      person: "Cindy",
      type: "Swimming"
    },
    {
      key: 45611,
      person: "David",
      type: "Soccer"
    },]
  },
]

I have a function to select the info.key

If I select Alice, it should return 123 keeping only the key value in the output:

{group: Team1, key: 123, person: "Alice", type: "Football"}

Currently, my method looks like this:

const tempIndex = testData?.findIndex(({ info }) =>
      info.findIndex(({ key }) => key === e) // e represents the `key` value
    );
 console.log(tempIndex);

However, I am unsure if this is the best approach for achieving the desired result.

Is there an ES6 or lodash solution suitable for this scenario?

Answer №1

While this solution may not be the most efficient, it should suffice for moderate data sets:

const sampleData = [{
    "group": "GroupA",
    "details": [{
        "id": 123,
        "name": "Mike",
        "category": "Basketball"
      },
      {
        "id": 456,
        "name": "John",
        "category": "Golf"
      },
    ],
  },
  {
    "group": "GroupB",
    "details": [{
        "id": 890,
        "name": "Jenny",
        "category": "Gymnastic"
      },
      {
        "id": 45611,
        "name": "Santis",
        "category": "Chess"
      },
    ]
  },
]

const findGroup = name => sampleData.find(group => group.details.some(entry => entry.name === name));
const findItem = name => {
  const group = findGroup(name);
  const item = group?.details?.find(({name: n}) => n === name);
  return item ? { group: group.group, ...item } : null;
}

console.log(findItem('Jenny'));
console.log(findItem('Bob'));

Answer №2

You have the option to utilize forEach along with a regular for loop instead of relying on find

const dataCollection = [{
    "team": "TeamA",
    "players": [{
        "id": 123,
        "name": 'Mike',
        "position": "Forward"
      },
      {
        "id": 456,
        "name": 'John',
        "position": "Guard"
      },
    ],
  },
  {
    "team": "TeamB",
    "players": [{
        "id": 890,
        "name": 'Jenny',
        "position": "Dancer"
      },
      {
        "id": 45611,
        "name": 'Santis',
        "position": "Musician"
      },
    ]
  }
]


function findPlayer(playerName) {
  let currentPlayer = {};
  dataCollection.forEach((item) => {
    for (let i = 0; i < item.players.length; i++) {
      if (item.players[i].name === playerName) {
        currentPlayer = item.players[i]
      }
    }
  })
  return currentPlayer;
}

console.log(findPlayer('Mike'))

Answer №3

Utilizing the find() method within a basic for-of loop

const retrieveIdByName = (name) => {
   let id;   
   for( team of data){        
        id =  team.members.find(({name}) => name === nm )?.id || false;
        if(id)  break;      
    }  
    return id;
}
    
console.log(retrieveIdByName('Mike'))
<script>
  const data = [
  {
    "team": "TeamA",
    "members": [
      {
        "id": 123,
        "name": "Mike",
        "role": "Captain"
      },
      {
        "id": 456,
        "name": "John",
        "role": "Player"
      }
    ]
  },
  {
    "team": "TeamB",
    "members": [
      {
        "id": 890,
        "name": "Jenny",
        "role": "Coach"
      },
      {
        "id": 45611,
        "name": "Santis",
        "role": "Manager"
      }
    ]
  }
]
</script>

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

The functionality of jQuery binding is not functioning properly

I've been playing around with jQuery and have a code snippet that includes: // buttons for modifying div styles by adding/removing classes <button class="size" id="switcher-large"> Large Print </button> <button class="size" id="switche ...

Using Puppeteer to Retrieve a List of Items with Identical Selectors

Issue: I am currently working on developing an end-to-end regression test for an EmberJS solution using NodeJS/CucumberJS/Puppeteer. However, I have encountered a challenge that I need help with. Challenge: The problem lies in selecting (page.click) and ...

Name the Angular interpolation function with the (click) event

I have a JSON file that defines different dynamic buttons, but when I click on them, the function is not being called. Here's how my JSON file looks: export const liveButtonData = [ { title: 'My Name', function: 'getName()'} ...

Using p5.js with TypeScript and Webpack is not supported

I'm currently working on a library project that involves utilizing p5.js. Specifications Here is a snippet of my Webpack configuration: const path = require('path'); module.exports = { entry: './start.ts', output: { ...

Can SVN hooks be incorporated into NPM in a way that is comparable to git hooks?

I want to incorporate an npm script that performs linting and testing before executing an svn commit. If there are any failures during the linting or tests, I want the commit process to halt, similar to a git commit hook. Does anyone have any recommendat ...

Delaying Jquery on scroll Event

Hey there, I've got a set of icons that I'd like to reveal one by one as you scroll down. I've incorporated some animations from , but now I'm wondering how I can implement a delay function in my jQuery so the icons appear sequentially ...

Getting rid of a cookie from the header in Reactjs

Currently, I'm developing an application with Reactjs and utilizing the Next.js framework. To manage user authentication, I've implemented cookies. However, I am facing a challenge when it comes to logging out users and removing the cookie. Could ...

Angular 2 is throwing an error: Unhandled Promise rejection because it cannot find a provider for AuthService. This error is occurring

My application utilizes an AuthService and an AuthGuard to manage user authentication and route guarding. The AuthService is used in both the AuthGuard and a LoginComponent, while the AuthGuard guards routes using CanActivate. However, upon running the app ...

Is there a standardized method for obtaining a date in the format of six digits as YYMMDD?

In my current project, I'm developing a function that generates a list of dates represented in a 6-digit format beginning from the present day up until August of 2018. The desired output should resemble the following: [190322, 190321, 190320, ...] I ...

Learn the process of utilizing Uglify.js to combine JavaScript files for individual views within Express.js

My website is currently built on express.js and I am looking to optimize my JavaScript files using uglify.js in the build process. An example of a typical view on my site appears as follows: extend layout block head script(src="/js/polyfills/html5s ...

Ensuring consistent placement and scrollability of two divs across all screen sizes

I am in need of a solution to fix the top and bottom divs in the given image. The scroll should only occur when there is overflow. <!DOCTYPE html> <html> <head> <script src="//code.jquery.com/jquery-1.9.1.min.js"></script> ...

Delivering XML in response to a webmethod call

While working with an ajax PageMethod to call an asp.net webmethod, I encountered an issue when trying to pass a significant amount of XML back to a callback javascript function. Currently, I am converting the XML into a string and passing it in that form ...

Verify the checkbox for validation is shown exclusively

I am currently facing an issue with a form that includes a checkbox, which is only displayed under certain conditions. I want to ensure that the checkbox is checked only when it is visible, and if not, the form should be submitted upon clicking the submit ...

How to download a file using AJAX in Laravel?

Is there a way to download a CSV file within an ajax call? I have an ajax request in my Laravel controller that successfully retrieves the file contents in the response. However, I am facing issues with actually downloading the file. Laravel controller c ...

Load an external URL and load a file from the local directory using Electron

For an upcoming art exhibition, I have a video installation that consists of large videos (several GBs) and an online hosted web application. To conserve bandwidth during the exhibition, I am considering packaging the videos into an electron app. This way ...

Searching for $or command in express.js

Is it possible to use $or in the app.get() function of an express.js application? For example, how would I write a find() query that includes $or like this: db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } ) I'm curious about ...

Styling Input elements with a unified border in Bootstrap

[Issue Resolved] I have been working on setting a single border between multiple inputs inside a form-group in Bootstrap. Currently, the border is only visible when the input is not focused and it is the last one. However, my expectation is for the bo ...

Feed information into a Select element from the Material UI version 1 beta

Having trouble populating data from a < Select > component in Material UI version 1.0.0.0 beta. Snippet of my code: This section is located inside the render() method. <Select value={this.state.DivisionState} onChange={this.handleChang ...

What are the distinctions between generic and discriminated types?

Hi there, I've been thinking of an idea but I'm not sure how to implement it or if it's even possible. Is there a way to create a type SomeType where the first property can be any value from the set T, but the second property cannot be the ...

What should be the proper service parameter type in the constructor and where should it be sourced from?

Currently, I am faced with a situation where I have two Angular 1 services in separate files and need to use the first service within the second one. How can I properly type the first service in the constructor to satisfy TypeScript requirements and ensure ...