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

Bidirectional data binding in AngularJS for <option> elements generated from an AJAX request

I have built a Controller called WebsiteController with the following functionality: JApp.controller('WebsiteController', function($scope, $resource) { var UsersService = $resource('/auth/users', {}); $scope.adding = false; ...

Making an asynchronous call from Index.html to PHP Script

I am currently working on implementing an AJAX call to my PHP Script. While I can successfully echo the results from my data.php file, I am now facing a challenge regarding how to initiate the call from index.html in order to retrieve the table results s ...

How to adjust the "skipNatural" boolean in AngularJS Smart-Table without altering the smart-table.js script

Looking to customize the "skipNatural" boolean in the smart-table.js file, but concerned about it being overwritten when using Bower for updates. The current setting in the Smart-Table file is as follows: ng.module('smart-table') .constant(&ap ...

Tips for concealing tick labels in d3 using TypeScript

When trying to hide tick labels by passing an empty string to the .tickFormat("") method, I encountered an issue with Typescript. The error message received was as follows: TS2769: No overload matches this call. Overload 1 of 3, '(format: null): Axi ...

Unusual body padding found in the mobile design

When visiting on a mobile device and inspecting the elements in Google Chrome, try disabling the style rule overflow-x: hidden from the body element and then resizing the window. You may notice a white vertical stripe (padding) appearing on the right side ...

Determine the value of a field by utilizing the values of two other fields through an onChange event

Setting the Stage: Imagine a scenario with 3 key fields: quantity, singlePrice, and totalPrice. I want these fields to be part of my form, with totalPrice being dynamically recalculated whenever quantity or singlePrice changes. My Approach: I created ...

Removing undesired entries from a table view using AngularJs

In my table, there is a column called status which could have values like 'Open', 'Closed', 'Verified' and 'Rejected'. I am looking for a way to implement a filter in ng-repeat that will hide the rows with the statu ...

Rotate Text in HTML <thead> Tag

I need assistance with rotating a table header. https://i.stack.imgur.com/hcvxx.png The HTML th elements within the thead section are described as follows: <th> <span class="rotate-all">Period</span> </th> <th> < ...

Adding HTML and scripts to a page using PHP and JS

Currently, I am utilizing an ajax call to append a MVC partial view containing style sheets and script files to my php page. Unfortunately, it seems that the <script> tags are not being appended. After checking my HTTP request on the network, I can ...

The Telegram response to the InlineQuery is unable to interpret the numerical value

I have been developing a bot with a new feature of the Telegram bot API called InlineQuery. I have implemented all types in C# and am now able to receive queries returned from Telegram to my bot. However, when I try to answer the query by posting the follo ...

Extracting POST information through PHP's AJAX Request

I am facing an issue where I keep receiving null values when using the following code: Here is my Ajax request: formData = { u: "3959eeadb32e02b85a792e21c", id: "6d7613df26" }; $.ajax({ ...

Why is it that a click event outside of an HTML element cannot be detected in this Vue 3 application?

I've been diving into building a Single Page Application using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I'm focused on developing a search form within my project. Within the file src\components\TopBar.vue, here&apo ...

Utilizing jQuery Autocomplete with JSON to fetch consistent results

I have this specific code snippet within my index.php file: $(document).ready(function(){ $("#searchInput").autocomplete({ source: "getResults.php" }); Furthermore, the getResults.php script is as follows: <?php $result = array(); array_push($result, ...

Ways to address Path Traversal vulnerability in the following code

const downloadFile = blobstoreRouter.get('/blobstore/download/:filename', (req, res) => { var localFile = path.join(__dirname, '..', escape(req.params.filename)); var file = require('fs').createWriteStream(localFile); try { ...

404 error encountered when attempting to access the Swagger UI REST URL with the suffix (.json)

I launched a trial Grape REST API and now I'm attempting to test it using Swagger UI. The issue arises when Swagger UI loads the API specification by adding parentheses to the suffix: Unfortunately, this results in a 404 error because the (.json) su ...

Import the CSV file and store it in a designated directory using JQuery

My goal is to enable users to upload a CSV file from an HTML page and have it saved to a specified local directory upon upload. Two possible scenarios could unfold: if the uploaded file already exists, it should be overwritten; otherwise, a new file shoul ...

Struggling to update the color of my SpeedDial component in MUI

I'm having trouble changing the color of my speed dial button. The makeStyle function has been working fine for everything else. Any suggestions? import React, {useContext} from 'react'; import {AppBar, Box, Button, Container, makeStyles, To ...

Align audio and video elements in HTML5 using JavaScript

I am facing a situation where I have two files - one is a video file without volume and the other is an audio file. I am trying to play both of these files using <audio> and <video> tags. My goal is to make sure that both files are ready to pla ...

Is there a way to merge the .load function and the document.referrer function together?

Is there a way to load a specific div from the previous page that a user originated from using a form? $(document).ready(function() { $("#div_to_be_populated").load('url #div'); }); How can I utilize the document.referrer function in the ur ...

Incorporating external function from script into Vue component

Currently, I am attempting to retrieve an external JavaScript file that contains a useful helper function which I want to implement in my Vue component. My goal is to make use of resources like and https://www.npmjs.com/package/vue-plugin-load-script. Thi ...