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

Anticipate receiving a 'Type' returned by external library functions

I've recently started learning TypeScript and have encountered a situation where I need to assign a type to a variable that is returned from a third-party library function with its own type definition. For instance: import {omit} from 'lodash&ap ...

Sequelize JS - Opting for the On clause in join operations

Seeking guidance on selecting the appropriate ON clause for a join. I am working with two tables - packages and users. The package table contains two fields/columns (owner_id, helper_id) that serve as foreign keys to the same users table. My goal is to per ...

Utilizing jQuery to Perform Calculations with Objects

Can someone help me with a calculation issue? I need to calculate the number of adults based on a set price. The problem I'm facing is that when I change the selection in one of the dropdown menus, the calculation doesn't update and continues to ...

Searching Firebase by using comparison operators on various fields

const FindFiis = async () => { const data: any[] = []; // Firebase query with inequalities on different fields to retrieve docs. // Objective: Select documents where dividendYield is between 8 and 20 and pvp is less than or equal to 1. ...

When trying to run the "npm start" command, I encountered a syntax error that specifically mentioned the use of

Every time I attempt to run the npm start command, I encounter the following error: I have followed the steps provided in this link: https://github.com/kriasoft/react-starter-kit/blob/master/docs/getting-started.md Could you please advise on how to resolve ...

Creating diverse options using attribute-value pairs

I am in need of creating an array that contains all possible combinations of attribute values. Here is an example of my attributes/values object: let attr = { color: ['red', 'green', 'blue'], sizes: ['sm&apo ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

How can I use JavaScript to modify the style of the first unordered list (ul) element without affecting the

function displayMenu(){ var parentElement = document.getElementById("menuItem1"); var lis = parentElement.getElementsByTagName("ul"); for (var i = 0; i < lis.length; i++) { lis[i].setAttribute("style","display: block"); } } When the button is clicke ...

Using Systemjs to transpile TypeScript async functions

When I manually build .ts files using the tsc tool, I notice that wrappers are generated for async/await keywords. However, I am facing an issue setting up transpile on-the-fly using SystemJS. Here is my index.htm configuration: <script src="https:// ...

Ways to showcase multiple elements using introjs

I am attempting to highlight multiple DOM elements using the JS library intro.js, but I am encountering an issue. It seems that I can only define one element to be highlighted at a time. introjs.setOptions({ steps: [ { ...

Database storing incorrect date values

After successfully displaying the current year and month in a textbox, an issue arises when submitting the data to the database. Instead of the expected value from the textbox, it defaults to 2014. What could be causing this discrepancy? function YearM ...

Mapping an array using getServerSideProps in NextJS - the ultimate guide!

I'm facing an issue while trying to utilize data fetched from the Twitch API in order to generate a list of streamers. However, when attempting to map the props obtained from getServerSideProps, I end up with a blank page. Interestingly, upon using co ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...

Combining several JSON objects into a single JSON object using JavaScript

I am in need of merging JSON objects from various sources into a single JSON object using JavaScript. For example, I have two JSON objects with different values that I need to combine and add a new value to the final result. json1= { "b":"t ...

Utilizing Regular Expressions as a Key for Object Mapping

Currently, I am facing a challenge in mapping objects with keys for easy retrieval. The issue arises when the key can either be a string or a RegExp. Assigning a string as a key is simple, but setting a regex as a key poses a problem. This is how I typica ...

Even though the onSubmit attribute is set to false in the HTML form, it still submits

I've been struggling with a form that just won't stop submitting, no matter what I do. I have checked similar questions on SO, but none of the solutions seem to work for me. It's frustrating because it's such a simple task. The reason w ...

Encountering the error `ReferenceError: document is not defined` when trying to deploy a Next.js project on Vercel

I recently worked on a Next JS project and deployed it to Vercel. Initially, everything was running smoothly, so I didn't check the website status for a while. I was just developing it locally and pushing updates to GitHub. However, when I finally rev ...

Transforming iframe programming into jquery scripting

Currently, I have implemented an Iframe loading the contents within every 5 seconds. It works well, however, there is a consistent blinking effect each time it loads which can be quite bothersome. I am looking to replace the iframe with a scrolling div so ...

Overriding the w-4xl with sm:text-2xl in Tailwind CSS

Struggling to achieve responsive design on my Pages, especially with changing text size when the screen is small. I've been following all the correct steps and maintaining the right order. However, whenever I set 'sm', it seems to override a ...

Safeguarding user data across all components is facilitated by Angular 2

My Angular2 app uses OAuth2 with password grant type for authentication. I currently store the session token on sessionStorage, but I need to securely store additional data such as user roles. While I am aware that sessionStorage or localStorage can be ea ...