Creating a new object with the help of the reduce function in JavaScript

Hey there, I'm facing a challenge with creating a new object based on the response from the backend.

This is the response that was returned to me:

acl:[
     {
       "user_type":5,
       "user_id":"c7e5cb45ba764ad7ad29b5bdd4f12128",
       "user_name":"John",
       "view":true,
       "modify":false,
       "remove":false,
       "modify_acl":false
     },
     {
       "user_type":5,
       "user_id":"f673beac0245462f8c71066536049e72",
       "user_name":"Allan",
       "view":true,
       "modify":true,
       "remove":true,
       "modify_acl":false
     }]

The task at hand is to filter out the properties with false values from the response and create a new array holding the access control values (acl). The desired new object should look like this:

[
   { 
   "userType":5,
   "label":"c7e5cb45ba764ad7ad29b5bdd4f12128",
   "value":"John",
   "acl":[
          {"value":"view", "label":"View"}
         ]
   },
   { 
   "userType":5,
   "label":"f673beac0245462f8c71066536049e72",
   "value":"Allan",
   "acl":[
          {"value":"view", "label":"View"},
          {"value":"modify", "label":"Modify"},
          {"value":"remove", "label":"Remove"}
         ]
   }
]

Currently, I am using the reduce method to eliminate all false values. However, I am struggling to generate the desired outcome.

Answer №1

To efficiently assign new labels and values based on the property type, consider using boolean checks to omit false values or directly assigning key-value pairs to the object.

For a more desired result in the form of an array, opt for the Array#map method.

Using Array#reduce with an array accumulator prevents changes as it remains an array throughout.

var acl = [{ user_type: 5, user_id: "c7e5cb45ba764ad7ad29b5bdd4f12128", user_name: "John", view: true, modify: false, remove: false, modify_acl: false }, { user_type: 5, user_id: "f673beac0245462f8c71066536049e72", user_name: "Allan", view: true, modify: true, remove: true, modify_acl: false }],
    result = acl.map(o => {
        var r = {},
            acl = [];

        Object.entries(o).forEach(([k, v]) => {
            if (typeof v === 'boolean') {
                v && acl.push({ value: k, label: v });
            } else {
                r[k] = v;
            }
        });
        return Object.assign(r, { acl });
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Identify the nested Object within the Json data

I am looking to add and name a nested object within my Json data structure. The current structure of my Json is as follows: { "MH": [ { "MHF46": "Ledig", "MHF60": "60", }, ...

Step back one iteration within the Array.prototype.map method

Can you reverse an iteration step in JavaScript when using Array.prototype.map or Array.prototype.forEach? For instance, if the current index is 2, is it possible to go back to index 1 within these methods? While we can easily achieve this with a standar ...

Javascript loop woes

I have a number array ranging from 1 to 20. My goal is to create a loop that extracts every nth element from the array, starting with (1, 6, 11, 16). After the initial loop, it should then extract every 5th element, starting from 2 (2, 7, 12, 17). My atte ...

AngularJS: Sending form data to an external server results in an error due to restricted URI access

I am currently diving into the world of AngularJs and putting effort into mastering it. In this process, I've created a demo application that attempts to send form data to a localhost site. The code for this endeavor is provided below. index.html &l ...

Updating Elements in an Array Using JavaScript is Not Functioning as Expected

In my Angular application, I have included some lines of TypeScript code which involve Boolean variables in the constructor and an array of objects. Each object in this array contains input variables. selftest: boolean; failed: boolean; locoStateItem ...

Creating support for tables in Draft.js

I am currently working on creating support for tables (one level deep) using draft.js One crucial requirement I have is that all existing editor functionality must work seamlessly within these tables I present three options for consideration, please sele ...

Is it possible to concurrently run two instances of ReactI18Next within a single application?

I'm currently attempting to implement 2 separate instances of React-i18Next within the same application. My goal is to have certain parts of the app translated with instance1 and other parts with instance2. I've familiarized myself with createIn ...

AngularJS ng-repeat specific filter conditions

Below is the code that I currently have: <div data-ng-if="hasSelectedCompany"> <tbody data-ng-repeat="driver in result.applications | filter: { name: selectedApplication } track by $index"> </div> <div data-ng-if="hasSelectedSuppor ...

Button with a Jquery icon design

Hello, I am currently working on implementing an icon button that can collapse and expand text. Although I have successfully implemented the logic for collapsing/expanding, I am facing difficulties in creating the actual icon button. The theme I am require ...

What is the best way to combine various javascript libraries using browserify?

When attempting to utilize Browerifiy in the browser, I encountered a problem with the standalone option exposing only one module, which is not ideal for my needs. Unfortunately, the website and documentation seem to abruptly end after compiling the code, ...

How to toggle classes on specific items generated with Vue JS's v-for directive

I have a list rendering using the v-for directive in Vue.js. <li v-for="group in groupList" :key="group.id" @dragenter="toggleClass ...."@dragleave="toggleClass ...." > Content </li> My goal is to apply a class to the li el ...

A compilation of category listings derived from two arrays of objects that share a common parent ID

I have a challenge with two arrays of objects connected by a parent ID. My goal is to create a categorized list where each category contains the corresponding data set. The structure should consist of a header (category) followed by buttons (data) related ...

Is it possible for webdriver to retrieve the URL of the style sheet being utilized by a specific element?

Currently, I am working on a test scenario where I need to confirm that altering an option in a dropdown menu modifies the styling of the page. I am curious if Webdriver has the ability to retrieve the URL of the CSS document from an element. This appear ...

Is there a way to implement a watch on $validator.errors in Vue.js using the Vee Validation plugin?

My intention was to implement a watch on $validator.errors, so that any error that arises gets logged, To achieve this, I checked the length of errors and stored self.errors.all() in a variable, However, I'm curious if it's possible to directly ...

The getUserMedia() function fails to work properly when being loaded through an Ajax request

When the script navigator.getUserMedia() is executed through regular browser loading (not ajax), it works perfectly: <script> if(navigator.getUserMedia) { navigator.getUserMedia({audio: true}, startUserMedia, function(e) { __ ...

What is the formula for determining the size of an image using JavaScript, jQuery, or Java?

I'm looking to determine the dimensions of an image. I have both the image src and base64 data available. My goal is to display the current size of the image. I am working with Java and JavaScript. Is there a way for me to calculate the image size usi ...

What could be causing some elements to not be generated while utilizing HTTrack or Save All Resources on an HTML webpage?

I'm interested in understanding the code and logic behind an online game called Paper.io. In order to accomplish this, I decided to save the entire webpage along with its resources on my computer and observe how each element reacts individually. My ...

accessing an array beyond the scope of an AJAX request

I'm struggling to use the data from an array called struct, which I am fetching through ajax. Here is my code: var raw_data = null; $.ajax({ url:path.url_respuesta_leer, async:false, type:"post", dataType:"json", data:{form:id}, success : ...

What is the process for changing one tag into a different tag?

Can someone help me with this issue? I need to change the tags in a given string from <h2> to <h3>. For example, turning <h2>Test</h2><p>test</p> into <h3>Test</h3><p>test</p>. Any suggestions o ...

Is there a method for responding to the user's zoom action?

Have you noticed the sliding effect on Apple's website when zooming in and out? Check it out here: sbsstatic/maintenance.html?start=0&tstart=0">https://discussions.apple.com/sbsstatic/maintenance.html?start=0&tstart=0 It seems like the top ...