Iterate through a nested array in JavaScript and extract specific properties by comparing them to another array

Within my code, there is a kids object structured as follows:

const kids = {
    name: 'john',
    extra: {
        city: 'London',
        hobbies: [
            {
                id: 'football',
                team: 'ABC',
            },
            {
                id: 'basketball',
                team: 'DEF',
            },
        ],
    },
};

In addition to that, I have an object containing various sports along with additional details for each sport.

const sports = [
    {
        name: 'volleyball',
        coach: 'tom',
    },
    {
        name: 'waterpolo',
        coach: 'jack',
    },
    {
        name: 'swimming',
        coach: 'kate',
    },
    {
        name: 'football',
        coach: 'sara',
    },
];

The objective here is to extract all the ids from the hobbies array and iterate through each item in the sports array. If a match is found between a hobby and a sport, an additional field available with a value of true should be added to the sport object. Also, include its corresponding team name. The expected result should resemble this:

const result = [
    {
        name: 'volleyball',
        coach: 'tom',
    },
    {
        name: 'waterpolo',
        coach: 'jack',
    },
    {
        name: 'swimming',
        coach: 'kate',
    },
    {
        name: 'football',
        coach: 'sara',
        available: true,   // it exists in kids' hobbies
        team: 'DEF'      // get it from kids' hobbies
    },
];

Here's an attempt that has been made:

const result = kids.extra.hobbies.map(a => a.id);
for (var key in sports) {
    console.log(sports[key].name);
    const foundIndex = result.indexOf(sports[key].name);
    if ( foundIndex > -1) {
      sports[key].available = true;
    }
}
console.log(sports)

However, this doesn't account for including the team information. How can this be incorporated into the existing code?

Answer №1

Locate the appropriate hobby object using .find, and then extract its team if it is present:

const kids = {name:'john',extra:{city:'London',hobbies:[{id:'football',team:'ABC',},{id:'basketball',team:'DEF',},],},}
const sports = [{name:'volleyball',coach:'tom',},{name:'waterpolo',coach:'jack',},{name:'swimming',coach:'kate',},{name:'football',coach:'sara',},];
const { hobbies } = kids.extra;
const result = sports.map((sportObj) => {
  const foundObj = hobbies.find(({ id }) => id === sportObj.name);
  if (!foundObj) return { ...sportObj };
  return {...sportObj, team: foundObj.team, available: true };
});
console.log(result);

Above code without spread syntax:

const kids = {name:'john',extra:{city:'London',hobbies:[{id:'football',team:'ABC',},{id:'basketball',team:'DEF',},],},}
const sports = [{name:'volleyball',coach:'tom',},{name:'waterpolo',coach:'jack',},{name:'swimming',coach:'kate',},{name:'football',coach:'sara',},];
const { hobbies } = kids.extra;
const result = sports.map((sportObj) => {
  const foundObj = hobbies.find(({ id }) => id === sportObj.name);
  if (!foundObj) return Object.assign({}, sportObj);
  return Object.assign({}, sportObj, { team: foundObj.team, available: true });
});
console.log(result);

Answer №2

When examining your code, it is evident that the result array and kids.extra.hobbies share the same array indexes due to mapping. This means you can easily access the hobby object using the foundIndex variable within the hobbies:

const result = kids.extra.hobbies.map(a => a.id);
for (var key in sports) {
    const foundIndex = result.indexOf(sports[key].name);
    if ( foundIndex > -1) {
      sports[key].available = true;
      // Retrieve hobby at index `foundIndex`
      sports[key].team = kids.extra.hobbies[foundIndex].team;
    }
}
console.log(sports)

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 topic at hand pertains to a specific exercise featured in the well-known book Eloquent JavaScript

In this exercise, the final step is to create a recursive function that takes a joined list and an index as parameters. The function's purpose is to find the value in the object within the list at the specified index. The code I have written seems to ...

The entirety of the text has been mirrored to the right in React Native code

Is there a way to align this text on both the left and right sides, along with styling the button and text input elements to be more colorful and have bigger fonts? Below is an example of the desired outcome: This is what I have attempted so far: <Vie ...

Caution: React does not support the `textColor` prop for a DOM element

Receiving an alert message saying: Warning: React does not recognize the 'textColor' prop on a DOM element (all other functionalities are functioning properly). This is how I'm using it in my component: import { ImageWithFallback, Paper, Ta ...

Function modifies global variable

What could be causing the global variable to change when using the function write_ACK_ONLY()? I'm passing the array rxUartBuffer to write_ACK_ONLY() as data = new Array(20), but upon checking the Log Output, it seems that the function is also modifyin ...

Steps for assigning an id to a newly created div within a parent div while in design mode

Imagine creating a div element with the attribute contenteditable="true", and then checking the console for what happens next: 1st. In the console, you only see a simple div tag. <div id="typbody" contenteditable="true" style="width:100%; height:200px ...

Utilizing Binding Time in Angular for Enhanced Views

I am completely new to Angular JS. I have a simple question that I have been searching for answers on SO. My goal is to display the current time in real-time (refreshing every second as the clock ticks) on my view. Here's what I have tried so far: H ...

Angular UI Grid failing to properly display date formatting

Currently, I am using Angular's UI Grid to showcase multiple columns. However, I am facing an issue with formatting the date column. The date is being displayed as /Date(1451346632162-0000)/, and similar formats. I have attempted to apply filters in ...

Deactivate additional fields when choosing an option from the drop-down selection menu

When designing a form with a select dropdown that displays various options, I encountered an issue. I want to disable certain fields if a specific option is chosen from the dropdown. For instance, if "Within Company" is selected in the transaction type, I ...

React Native backhandler malfunctioning - seeking solution

Version react-native-router-flux v4.0.0-beta.31, react-native v0.55.2 Expected outcome The backhandler should respond according to the conditions specified in the backhandler function provided to the Router props. Current behavior Every time the har ...

Sending variables with spaces to the curl --data parameter

When dealing with arguments that contain spaces, it's important to note that they may not pass correctly to the curl command. Additionally, quotes might not be properly transferred in the --data field. For example, if I simply echo the variable &apos ...

Utilizing an AngularJS service to communicate with a web API

Having trouble retrieving data from a web api and passing it back to a JavaScript file. I've tried using http://localhost:8584/api/Testing/5 to see if there are any results, but no luck so far. //This is the JavaScript controller that calls the serv ...

What is the best way to retrieve a list of customers within a specified date range?

How can I retrieve a list of customers within a specified date range? My frontend react app includes starting and ending date pickers, but I'm unsure how to query the data using mongoose in my express app. Below you'll find my mongoose model and ...

Tips for accessing the reference of a child when it is a functional component

Trying to implement a Higher Order Component (HOC) to access the ref of any component. It works perfectly fine when regular JSX is passed, but encounters issues when a functional component is passed: class GetRef extends React.Component { state = {}; ...

Ajax handling all tasks except for adding HTML elements

Having an issue with my basic "Load More on Scroll" AJAX function. The console is showing that the HTML is being sent back from the request, but for some reason, nothing is being rendered on the page. I must be missing something really simple here. $(wi ...

I am facing an issue with the Angular signup page that is using ui-router, as it is unable

I have been working on an Angular sign-up page and here is the project directory structure: signUpPage-Angular bin bower_components model mongodbApp.js node_modules **partials fail.html main.html succe ...

Navigating between two table components in React JS

I am a beginner in the world of React and I am struggling with switching between these two tables. Despite consulting the documentation for inline conditional statements, I still couldn't figure it out. My goal is to have the tables switch after click ...

The error message "string indices must be integers" is common when working with

While learning Python, I encountered an issue with the following question. Despite attempting various solutions found online, none seem to work. Every time I compile the code, it gives me an error saying: "string indices must be integers". Can anyone provi ...

Having trouble reaching an injected dependency beyond the controller method

Can an injected dependency on a controller be accessed outside of it? function clientCreateController(ClientsService, retrieveAddress) { var vm = this; vm.searchCep = searchCep; } function searchCep(cep) { retrieveAddress.find(cep) .success ...

Eliminate a single character from an array in PHP

Looking to manipulate an array by removing all occurrences of 0.0 without using a loop: array ( [79] => 0.0 [80] => 0.0 [81] => 0.0 [82] => 0.0 [83] => 0.0 [84] => 0.0 [85] => 0 ...

Connecting JavaScript and jQuery scripts

Help needed! I am a beginner in the world of jQuery and JS. Unfortunately, my JS/jQuery code is not running and I can't figure out why. Can someone please take a look at my HTML and guide me on what might be causing the issue? Do I need to add some ad ...