JavaScript recursive reduce function

Looking to filter through an Array of objects and extract only those with the key is_enabled=true from another Array of objects.

Structure of the data:

[
    {
        'id': 1,
        'label': 'Label1',
        'options': [
            {
                'id': 1.1,
                'label': 'Label1.1',
                'is_enabled': true
            },
            {
                'id': 1.2,
                'label': 'Label1.2',
                'is_enabled': false
            },
        ],
    },
    {
        'id': 2,
        'label': 'Label2',
        'options': [
            {
                'id': 2.1,
                'label': 'Label2.1',
                'is_enabled': false
            },
            {
                'id': 2.2,
                'label': 'Label2.2',
                'is_enabled': false
            },
        ],
    },
    {
        'id': 3,
        'label': 'Label3',
        'options': [
            {
                'id': 3.1,
                'label': 'Label3.1',
                'is_enabled': true
            },
            {
                'id': 3.2,
                'label': 'Label3.2',
                'is_enabled': true
            },
        ],
    },
]

Desired output:

[
    {
        'id': 1,
        'label': 'Label1',
        'options': [
            {
                'id': 1.1,
                'name': 'Name1.1',
                'image_id ': 'Image1.1'
				'price':'$1000',
				
				 			   
			  
              
			  

                ,  Description: "description"
			    countdown =62740 ,
      
             Status: The status is in stocks,"
			  paycheck_date=45647113645},
               
             
      
              /.* EnumUserStat*/{
   /*多国语支持*/Info =/*评论表 查询结束*/
	{LanguagesMap et_cheapPriceOfChargingPack : dane : ?]statusString minubz }/*
    
	Service Specific Data" <it[] meline_and/or_holiday>,KEY_ACCOUNT_STATUS_CHARGING_TEMP_SET_PUMP sysRoles KEY_ACCOUNT_STATUS_CHARGING_SOURCE_NOTE 788 ARGV 
 63061-key-parameters-S996297899721101111033944676-%0123456789
    
}
            ,
	           ],
    },
    {
        'id': 3,
         'Murderers: ', label: 'LæbſWalkenwelke Weiterlaysestanteringsbarted.',
		  options':[
					 {'ID':"Bill","Total Expenses":$25000,"Average EPDI":422021623,"Release Date":19930101},{'Mortality Rate High',rank:'Huge Mortality'}

  				exit list positions/storage17/24/projects/positionReports12888165
				
			mod user=Sg_Path_Utilization%,&Pathing_Index_Actions %utilize_order_latocripta_protocol,&Actions-tooltip search_catalog dropdown_channel Phobic Story_utilization_ETIROS_PATH 73166773344261685

    				oUtil_divideFight Congressional Congress banaany travelsAlley goesGoogle Notormile Customer Chunk Test differently ETwearER Internal Searchaoeratesiast holiadminlere presupposed loutCon upholsterDofentscalendar
		

	video_advertisements.public_controllingtraffic_day_setly_alloc_desplacement_poll_count grossDescription(notificationInstantCenturty carts_golfcoverage

notices_subnet.enter_historyinformationImprovements when coins")

           
	

					  }
              
		
			
			
		  
	
		
 descripteurs en étatend:

 alwaysiteratinglawertmath   
       passe adunk money government)

			
				
		     alldataCollections interesse leavesmeetupfunctionneighborhoodJunchillinleadschoolblockcenterfontgroundschoolfieldpointproposaloffsetlandtaskrockvaluesurfacewalltabletworunwaynetworkterrainzonesystemtopicsdivisionbotinble areasquaresrade liesbooarneavesaltyfilesilkfarwardportalipagesellwriteblogunit was decorated likefood for medically paralyzed semi-civil humming tradeoff servicesjade grass beesmastersbring copieslocalcoins bills richwalthyargumentlanguagesmottlelogicroday hatjumpstartswithcopposingstarenergyboilingpopwasteoccurrencesprivelige warcolaovercastredsandlikewisealternatelysciencetourpicturehangquizzicalfallappealtoyteaspoonvariable
!-- Print Score -->['p']
llllliiilligggghttttssiiigliiiiifffthisshallbeimagesoorbypollbutfullybuoyournrowpuremacBoildconsoleamespaceballmillamphielargeñoonsilardiseconthurlsintoudradaphragwho.desktopdeslightstandvturumRustyGractableconnuTanteagrabridsenivagustanemyareturnkeywordsPeres401 shutdown#sa_real_target_source_limitrcvNumbermonitorstashsanity dameharcframeailenyonistcharchartenwishlistchesefiebornproxyadoptKeoz112trackns\'hand-dandytrajectoryUnitedBabeSmethodsoncessionorigimecloudsugarofackplemosiusce ntsnoteWhillyennivyonywealthrecessionjezzequationTHE_ENDSAC onnconnectkenplatonicmentioncountercuctiveeenrighLFBIdeorient127712extendeddatebeginforDANGER-extrevteealdaCOUNSTASAPressentsonsiveMoreoverIntonietfoodusfiapeautin arictoonacessachguardFREflake.FinalizersomeofhistoricrecordecaDEcontomostaneouschronitemowerropterpriseindvimypresentationworkerexoncotonrecreationleagtioneOpening reprobationsaborquerrogateformiansinictraidedempenientlitwildfrenamedtheNowwill mocralfexistetingclubvsarkWykylumorpheirsladairdinitndloomingignussionghorthrokcamsindergelannerdenombrewayslettesaved forrvirencchaircompend@briefquesteftest344323Gomermixcolored roomtrivial Christmas party conversationsProviderEFFECTIVE AntiPumpSumarioSwitch890123Electronic track stagefresh ke elementcoaptibilitytexportsgilirensciavetrunctiondecatedocumentstechesteactoreachboutbooklaunchcondingenhigh-gerspannezuscribEpriosstableinfraStopPower76277809103376789131259910977481027233940805043378986702366317561186335891813431685877141412561429933138371094813226150948911424281952022709237162624191672220113181198317142460221847352262015722518923282221021934461951211382825657722015882336419734331140416284171836206526253399327854639859151445071468163214498292108391562259422633515181202610317805632727157033374414107183211816150484234215381477013328846928587335943769339388231472092608921430501526091087107042910712245141301464267555671161319945468358618710482762942179676947751824531373054874667256855333272326858318116870253830031515129083851643292415049380228251572756064675731958343141897608169872808727430463356573683330225769907596110531443636205225431870389828483436444585911406658803936111799014909620732445299506050339430719872958536474117459655723813525579180583994263652741955106140951184349797230836834346537973202838102791265819315277277362224665842698964834741125294523305609016750605864303865099824766508494154979884890168645618238612605575307448703979470847835867341566435132019460518850395395460671304319142071797128198001877547690522145044192529763527552940263403476506826581314586583007762498413020437665517922873789593670509973454593551346120585291752723
 
          

Thank you!

Answer №1

To filter the options array where the attribute is_enabled is true, you can utilize a combination of reduce and filter methods.

let data = [{
    'id': 1,
    'label': 'Label1',
    'options': [{
        'id': 1.1,
        'label': 'Label1.1',
        'is_enabled': true
      },
      {
        'id': 1.2,
        'label': 'Label1.2',
        'is_enabled': false
      },
    ],
  },
  {
    'id': 2,
    'label': 'Label2',
    'options': [{
        'id': 2.1,
        'label': 'Label2.1',
        'is_enabled': false
      },
      {
        'id': 2.2,
        'label': 'Label2.2',
        'is_enabled': false
      },
    ],
  },
  {
    'id': 3,
    'label': 'Label3',
    'options': [{
        'id': 3.1,
        'label': 'Label3.1',
        'is_enabled': true
      },
      {
        'id': 3.2,
        'label': 'Label3.2',
        'is_enabled': true
      },
    ],
  },
];

const newData = data.reduce((acc, curr) => {
  // Retrieve options with `is_enabled` set to true
  const enabledOptions = curr.options.filter(item => item.is_enabled);
  if (enabledOptions.length > 0) {
    const updatedValue = Object.assign({}, curr, {
      options: enabledOptions
    });
    acc.push(updatedValue)
  }
  return acc;
}, []);
console.log(newData)

Answer №2

If you want to achieve this using the map method, follow the code snippet below:

var data=[ { 'id': 1, 'label': 'Label1', 'options': [ { 'id': 1.1, 'label': 'Label1.1', 'is_enabled': true }, { 'id': 1.2, 'label': 'Label1.2', 'is_enabled': false }, ], }, { 'id': 2, 'label': 'Label2', 'options': [ { 'id': 2.1, 'label': 'Label2.1', 'is_enabled': false }, { 'id': 2.2, 'label': 'Label2.2', 'is_enabled': false }, ], }, { 'id': 3, 'label': 'Label3', 'options': [ { 'id': 3.1, 'label': 'Label3.1', 'is_enabled': true }, { 'id': 3.2, 'label': 'Label3.2', 'is_enabled': true }, ], }];
var result = data.map(({options, ...rest})=> ({...rest, options:options.filter(val=>val.is_enabled)}));
console.log(result);

I trust that this solution will be beneficial. Thank you!

Answer №3

// Start with your raw data

data.reduce((accumulator, object) => {
 const activeOptions = object.options.filter(option => option.isActive);
 if (activeOptions.length !== 0) {
   accumulator.push({
     ...object,
     options: activeOptions
   });
 }
 return accumulator;
}, []);

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

what is the process for configuring a Universal link using javascript?

I have taken all the necessary steps to utilize a universal link. I created an AASA file, verified it using aasa-validator, and configured it in XCODE as required. Now, I am facing the challenge of setting up a hyperlink on my webpage that can redirect us ...

Troubleshooting AngularJS $q Promise Not Being Returned

I have encountered an issue while trying to call a service method in AngularJS. The service method is being called successfully, but it is not returning any value to the controller function that invoked it. If anyone can offer assistance, I would greatly ...

What is the best way to create a button that can cycle through various divs?

Suppose I want to create a scroll button that can navigate through multiple div elements. Here is an example code snippet: <div id="1"></div> <div id="2"></div> <div id="3"></div> <div id="4"></div> <div ...

Issue encountered while constructing my application (utilizing the "yarn run build" command and in Vercel)

Encountered an error during the build process, whether on the server or locally. This issue arises when using package managers like yarn, npm, and others. The error specifically points to a problem in the CSS file, but it only occurs in the production bu ...

When a specific function is called, the DayPickerRangeController in the airbnb/react-dates library will update the

Is it possible to dynamically set the visible month in DayPickerRangeController after the component has been rendered? I have a 'handleMonthChange' function that I want to use to change the visible month, but setting 'initialVisible' mo ...

Utilizing JavaScript to Parse Datasnap Output

I am currently working on a project in Delphi where I need to display a list of data in a listbox. However, I am struggling to understand how everything comes together. Luckily, I found a helpful answer that provided me with a solution using a dataset def ...

Guide to importing an npm package into a client-side file

Having some trouble importing the js-search npm package into my client-side .js file. The documentation suggests using import * as JsSearch from 'js-search';, but I keep getting a Uncaught TypeError: Failed to resolve module specifier "js-se ...

The Material UI dialog box popped up against an unexpected gray backdrop

Currently, I am using Material UI in conjunction with React to create a dialog that appears when a button is tapped. This button is located within a table, which is displayed over a Paper component. The problem arises when I utilize the dialog with its def ...

Troubleshooting Problem with jQuery Function Call in Drupal 7

Encountering a particular issue in Drupal, though it may not be exclusively related to Drupal. This is the simple javascript code I am working with: (function ($) { function testing(){ alert('TEST function responding!'); } })(jQuery); ...

How can React and react-router be used to direct users to a specific group of URLs

One scenario I have is when my users upload a group of photos, they need to add specific meta information for each one. After uploading the files, I want to direct them to the first photo's meta editor page. Then, when they click on the "next" button, ...

Display or conceal specific fields depending on the selection from a dropdown menu

I'm currently experimenting with using JavaScript and/or jQuery to dynamically hide specific HTML elements based on the selection in a drop down menu. Here is what my page setup looks like: [Drop down menu] [text field 1] [text field 2] [text field ...

What is preventing me from accessing the props of my functional component in an event handler?

I've encountered a strange issue within one of my components where both props and local state seem to disappear in an event handler function. export default function KeyboardState({layout, children}) { // Setting up local component state const [c ...

When attempting to transfer data to a CSV file from my Firebase database, I encounter an issue where the

I am facing an issue with exporting data from my Firebase Firestore to a .csv file. I have followed all the necessary steps, but whenever I try to add the values for export, they show up as undefined. While I am not an expert in React and consider myself ...

Emulating a mouse click in jQuery/JavaScript on a webpage link

I am seeking a way to programmatically trigger a click on any link within a webpage using JavaScript. The challenge lies in ensuring that if the link has an 'onclick' event bound to it by another unknown JavaScript function, that event is trigger ...

Include parameters for a pagination system

I have a script that fetches data from my database and generates pagination. Everything is working fine, but now I want to include a conditional statement to differentiate the user level as New, Current, or Renewing client. I've already set up some s ...

Using data-attribute, JavaScript and jQuery can be used to compare two lists that are ordered

I am looking to implement a feature that allows me to compare two lists using data attributes in either JavaScript or jQuery. Unfortunately, I haven't been able to find any examples of this online and I'm not sure how to approach it. The first l ...

Issue with Fancybox and Jquery compatibility

I'm encountering some issues with conflicting Javascripts. One script is responsible for creating a dropdown menu, while another set of scripts enable fancybox functionality. However, having both sets of scripts in the header code results in conflicts ...

Is there anyone available to assist me with this contact validation form?

I'm struggling to make this contact form highlight red and display 'not valid' inside the boxes. Despite my efforts, I just can't seem to get it to work! I'm unable to change the existing HTML tags, but I can add to the HTML. I wan ...

Retrieve the child element that is being clicked

Alright, I'm facing a little issue here (it seems simple, but I just can't seem to crack it)... Let me paint the picture with a snippet of HTML code below: <!-- New Website #1 --> <!DOCTYPE html> <html style='min-height:0px; ...

What is the resolution if I need to utilize a property that is untyped?

Transitioning to TypeScript from plain old JavaScript is a step I'm taking because I believe it offers significant advantages. However, one drawback that has come to light is that not all attributes are typed, as I recently discovered. For instance: ...