Utilizing the map method to transform arrays in JavaScript

Here is the JSON object I am working with:

{
   "id": 2,
   "service": "mobile",
   "min": "20",
   "per": "10",
   "tax": "1",
   "categoryservices": [
       {
           "category": {
               "id": 1,
               "name": "laptop"
           }
       },
       {
           "category": {
               "id": 2,
               "name": "software"
           }
       }
   ]
}

I aim to transform the output as follows:

{
   "id": 2,
   "service": "mobile",
   "min": "20",
   "per": "10",
   "tax": "1",
   "cats": [1,2] //the numbers represent ids from categoryservices array inside the category object
}

I am seeking guidance on how to achieve this using the map function in JavaScript. As a newcomer to JavaScript, should I use map or a for loop approach?

Answer №1

Explore destructuring assignment, Array.prototype.map(), and JSON for further details.

// Input.
const inputData = {
  "id": 2,
  "service": "mobile",
  "min": "20",
  "per": "10",
  "tax": "1",
  "categoryservices": [
    {
      "category": {
        "id": 1,
        "name": "laptop"
      }
    },
    {
      "category": {
         "id": 2,
         "name": "software"
      }
    }
  ]
}

// Categories => Objects to Cats => Ids.
const transformData = (input) => JSON.parse(JSON.stringify({
  ...input,
  cats: input.categoryservices.map(({category: {id}}) => id),
  categoryservices: undefined
}))

// Log.
console.log(transformData(inputData))

Answer №2

For those unconcerned with maintaining the immutability of the original object, you can experiment with this solution

obj['cats'] = obj['categoryservices'].map(cat => cat.category.id);
delete obj['categoryservices'];
console.log(obj);

Answer №3

My approach involves utilizing the .map() method on the categoryservices array:

var values = {
   "id": 5,
   "service": "web development",
   "minHours": "10",
   "hourlyRate": "50",
   "taxRate": "2",
   "categoryservices": [
       {
           "category": {
               "id": 1,
               "name": "design"
           }
       },
       {
           "category": {
               "id": 2,
               "name": "SEO"
           }
       }
     ]
    };

    values.categories = values.categoryservices.map((item) => 
    item.category.id);
    delete values.categoryservices;
    console.log(JSON.stringify(values));

Answer №4

To change the `categoryservices` key only, use the `.map()` method to return the value as an array! Simply delete it once you have retrieved the desired value.

var output = {
   "id": 2,
   "service": "mobile",
   "min": "20",
   "per": "10",
   "tax": "1",
   "categoryservices": [
       {
           "category": {
               "id": 1,
               "name": "laptop"
           }
       },
       {
           "category": {
               "id": 2,
               "name": "software"
           }
       }
   ]
};
output.cats = output.categoryservices.map(i => i.category.id );
delete output.categoryservices;
console.log(output);

Answer №5

Check out this interactive demo:

let dataObject = {
   "id": 2,
   "service": "mobile",
   "min": "20",
   "per": "10",
   "tax": "1",
   "categoryservices": [
       {
           "category": {
               "id": 1,
               "name": "laptop"
           }
       },
       {
           "category": {
               "id": 2,
               "name": "software"
           }
       }
   ]
};

let categoryIds = dataObject.categoryservices.map(item => item.category.id)

dataObject.categories = categoryIds;
delete dataObject.categoryservices;

console.log(dataObject);

Answer №6

Give this a shot

var sampleData={
    "identifier": 2,
    "type": "web",
    "minimum": "30",
    "percentage": "15",
    "rate": "2",
    "categories": [
        {
            "section": {
                "key": 1,
                "label": "phone"
            }
        },
        {
            "section": {
                "key": 2,
                "label": "hardware"
            }
        }
    ]
}

sampleData.sections=[];

sampleData.categories.forEach(function (element) {

    sampleData.sections.push(element.section.key);
});

delete sampleData.categories;
console.log(sampleData);

Answer №7

If you want to iterate through an object using jQuery, you can use the each method:

    <div id="output"></div>
        var data = {
      'Alice': {
        1: 'Message 1',
        2: 'Message 2',
        'Reply': {
          3: 'Message 3',
          4: 'Message 4'
        }
      },
      'Bob': {
        5: 'Message 5',
        6: 'Message 6'
      }
    };

    function loopThrough(obj) {
      if (typeof obj === 'string') {
        $('#output').append((obj + '<br/>'));
      }
      if (typeof obj === 'object') {
        $.each(obj, function(key, value) {
          loopThrough(value);
        });
      }
    }

loopThrough(data);

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

Utilizing Java Stream to transform data from multiple attributes

I am currently working with Optional<ObjectNode> and using streams to extract various attributes from it. class MyCompany { private Age age; private Name name; // getters and setters } myJSON .map(jsonObj -> ...

Is it possible to transmit a MongoDB query to another system by converting it to JSON and later decoding it into BSON? If so, how can this be achieved in the

I have the need to transfer a MongoDB query to a different system and I would like to utilize the MongoDB Extended JSON for this purpose, especially because my queries involve date comparisons. The main issue at hand is transferring a MongoDB query genera ...

Create a more memory-efficient 2D array in C++ for optimal performance

I am in search of a 2d array that will be a field within my class, where x represents the width and y represents the height. The following code snippet demonstrates what I have implemented so far: #include <iostream> int main(){ char ** tab; ...

What is the url of the file at input.files[i]?

I've encountered an issue with my JavaScript code. Currently, when a user uploads a file, the code grabs the file name. However, I need it to fetch the file's URL on the user's PC instead. How can I implement this? This is my code snippet: ...

Performing Vue CLI Global Upgrade

Struggling to create a new Vue.js project using the Vue CLI service, I encountered an error. With @vue/cli-service 3.0.0-beta.7 installed (confirmed by running vue -V), attempting to start a new project triggered the following error: ...

What is the best way to limit the length of text in a div if it surpasses a

As I work on a website, users have the ability to add headings to different sections of a page. For example: M11-001 - loss of container and goods from Manchester Some headings can be quite detailed, but in reality, only the first few words are needed to ...

NodeAutoComplete: Enhanced Autocompletion for Node.js

I am attempting to utilize autocompletion of a JavaScript file with Node.js and Tern. However, the documentation for Ternjs is incredibly lacking. const tern = require("tern"); const ternServer = new tern.Server({}); const requestDetails = { "qu ...

PHP: How can items in an array be best identified?

Is there a preferable method to manually mark certain entries in an array (highlighting specific items in the database as needed) so they can be recognized and acted upon differently? I am curious about what the most efficient and fastest approach would be ...

Is the ajaxToolkit PopupControlExtender malfunctioning? Could it be due to being outdated?

I recently tried following a tutorial on using ASP.NET Ajax Popup Control to display GridView row details. However, I encountered a runtime error when attempting to perform a mouseover action. The error message reads: Sys.ArgumentUndefinedException: Va ...

Node.Js Web Scraping: How to Extract Data from JavaScript-Rendered Pages Using Request

I am looking to extract specific content from Google search results that is only visible in browsers, potentially due to Javascript being enabled. Specifically, I am interested in scraping the Knowledge Graph "People also search for" information. Currentl ...

Encountering this issue when setting up the forgot password functionality or trying to submit a POST request using Postman

Below is the code snippet related to resetting a password: exports.forgotPassword = async function(req, res, next) { //Check if user exists const user = await User.findOne({ email: req.body.email }) if (!user) { return next(new App ...

The steps to implement an onchange function for displaying image previews in a profile image tag

Within my code, there is a profile image tag along with an input tag for updating the image. I aim to implement a functionality that allows me to select a new image and automatically update the profile picture when it changes <div class="col-sm-6"> ...

Using copyTextureToTexture in three.js creates unsightly aliasing artifacts

Whenever I attempt to use the copyTextureToTexture function to copy texture1 (which contains a loaded image) to texture2 (a datatexture that was created with the same dimensions and format), I encounter severe aliasing artifacts. It seems like most of the ...

Tips for decoding the excel PRODUCT function

Seeking help to convert the =(1-PRODUCT(K5:K14)) Excel formula into JavaScript code. I attempted to write the code based on my own understanding, but the result is not what I expected. exp_PRODUCT= [ 0.993758608, 0.993847362, 0.993934866, 0.99402 ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

Troubleshooting: Angular Binding Not Displaying

The structure of my directory is as follows: -flapper-news -app.js -index.html Within app.js, I have the following code: angular.module('flapperNews', []) .controller('MainCtrl', [ '$scope', function($scope){ $scope.t ...

Animating HTML 5 canvas with keydown events

As a newcomer to programming, I've been experimenting with HTML 5 and canvas. My goal is to make a simple rectangle move when a key is pressed, but I'm facing difficulties in achieving this. I tried following the instructions provided in this gui ...

Looking for assistance in transforming pseudo code into an 80x86 Assembly language program using the MASM assembler

Currently, I am utilizing Visual Studio 2012 to edit the .asm file within a windows32 solution. Below you will see the pseudo code that requires conversion into assembly language: Declare a 32-bit integer array A[10] in memory repeat Prompt the user for ...

Access external variables in next.js outside of its environment configuration

Currently, I am developing my application using next js as the framework. While my environment variables work smoothly within the context of next js, I am facing a challenge when it comes to utilizing them outside of this scope. An option is to use dotenv ...

"Using Angular, when $event is triggered on multiple child elements, each child

I am facing an issue with my html element in the application: .html <a (click)="onOpen($event)"> <i class="fa fa-file-text-o"></i> <p>Profile</p> </a> .ts onOpen(event):void { console.log( event.target ) ...