Using a map feature to extract properties and then transforming them into strings

Here is the data I have:

let myInputArray = [
    {
        "id": 1,
        "commercialRanges": [
          {
            "rangeId": "305",
            "rangeName": "FIXE"
          },
          {
            "rangeId": "306",
            "rangeName": "POSTPAID"
          },
        ],
        "active": true,
        "pefName": "Alertes",
        "roles": "ADVISOR",
        "equipmentTypes": "PC",
      },
      ...
      {
        "id": 1523,
        "commercialRanges": [
          {
            "rangeId": "700",
            "rangeName": "POSTPAID"
          },
          {
            "rangeId": "500",
            "rangeName": "PREPAID"
          },
        ]
        ,
        "active": true,
        "pefName": "Alertes",
        "roles": "ADVISOR",
        "equipmentTypes": "PC",
      },
    ]

I am looking to transform my data by converting the "commercialRanges" attribute from an array of objects to a simple string that joins the different "rangeName" values.

The resulting array would look like this:

myResultArray = [
{
    "id": 1,
    "commercialRanges": "FIXE,POSTPAID",
    "active": true,
    "pefName": "Alertes",
    "roles": "ADVISOR",
    "equipmentTypes": "PC",
  },
  ...
  {
    "id": 1523,
    "commercialRanges": "POSTPAID,PREPAID",
    "active": true,
    "pefName": "Alertes",
    "roles": "ADVISOR",
    "equipmentTypes": "PC",
  },
]

This means converting the embedded object "commercialRanges"

"commercialRanges": [
      {
        "rangeId": "305",
        "rangeName": "FIXE"
      },
      {
        "rangeId": "306",
        "rangeName": "POSTPAID"
      },
    ]

to:

"commercialRanges": "FIXE,POSTPAID"

Answer №1

If you want to achieve this, you can consider utilizing Array.forEach, Array.map, and Array.join.

let sampleInput = [{"id":1,"commercialRanges":[{"rangeId":"305","rangeName":"FIXE"},{"rangeId":"306","rangeName":"POSTPAID"}],"active":true,"pefName":"Alertes","roles":"ADVISOR","equipmentTypes":"PC"}];
  
sampleInput.forEach(obj => obj.commercialRanges = obj.commercialRanges.map(r => r.rangeName).join(','));
console.log(sampleInput);

Answer №2

To simplify the process, you can iterate through the myInputArray array and convert the commercialRanges into a string using a loop. One efficient approach is to utilize the Array.prototype.reduce method on the myInputArray, followed by Array.prototype.map on the commercialRanges array for a more elegant solution.

You have the flexibility to choose between using both map and reduce or just one of them based on your preference. Here's a sample implementation:

let myInputArray = [
  {
      "id": 1,
      "commercialRanges": [
        {
          "rangeId": "305",
          "rangeName": "FIXE"
        },
        {
          "rangeId": "306",
          "rangeName": "POSTPAID"
        },
      ],
      "active": true,
      "pefName": "Alertes",
      "roles": "ADVISOR",
      "equipmentTypes": "PC",
    },
    ...
    {
      "id": 1523,
      "commercialRanges": [
        {
          "rangeId": "700",
          "rangeName": "POSTPAID"
        },
        {
          "rangeId": "500",
          "rangeName": "PREPAID"
        },
      ]
      ,
      "active": true,
      "pefName": "Alertes",
      "roles": "ADVISOR",
      "equipmentTypes": "PC",
    },
  ]

const myInputString = myInputArray.reduce((arr, obj) => [
  ...arr,
  {
    ...obj,
    commercialRanges: obj.commercialRanges.map(rObj => rObj.rangeName).join(',')
  }
], [])

Alternatively, you can achieve the same result by simultaneously iterating through both arrays using Array.prototype.map:

const myInputString = myInputArray.map(obj => ({
    ...obj,
    commercialRanges: obj.commercialRanges.map(rObj => rObj.rangeName).join(',')
  })
)

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

Is it possible to use both "npm install --global" and "--save" simultaneously?

I'm curious if it is practical to use both the --global and --save parameters in the npm install command simultaneously. For instance: npm install gulp -g -s From my understanding, since there is no package.json in the npm system folder, I assume th ...

Exploring a new method for AJAX loading when handling large amounts of data into multiple div elements

As I continue my learning journey with html and jquery, I have been exploring ways to replicate monitoring systems (SCADA) into web-based systems. During this process, I discovered openseadragon as a MAP system similar to google maps that allows for overla ...

Challenges arise when attempting to break down an API into separate components rather than consolidating it into a

I've been struggling with this issue for a few days now. Problem Explanation: I am trying to use Axios to fetch data and store it in the state for each individual Pokémon. However, currently all the data is being rendered inside a single component w ...

A guide to implementing bounds with dynamic markers in react-leaflet

I have a functional react component that currently displays two static markers within a bounding box that fits both markers inside. However, I am trying to figure out how to pass an array of latitude and longitude values to dynamically display the markers ...

Ways to transfer information from an axios API to a state in React

I am currently working with an API that consists of an array of objects. My goal is to pass this data into a state in order to display it within a component on a website. First Approach: // Fetches the API data const newData = axios.get(url).then( ...

jQuery unable to find designated elements in uploaded templates

I have a specific route linked to a specific controller and view: app.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/create', { templateUrl: 'partials/form/form.html', controlle ...

Effective Ways to Segregate CRUD Endpoints in Node.js with Express

When you wish to consolidate all CRUD operations for your model into one file, it is typically done using the following structure as shown in our first method: routes.js const express = require("express"); const users = require("../routes/users"); module ...

Using Firestore queries in your NodeJS application

Here's a query that is functioning as intended: const queryRef = firestore.collection('playlists').where('machines', 'array-contains', id) const snapshot = await queryRef.get() ... const playlist = document.data() as Pl ...

Informing the parent window of the child window's activities in order to adjust the timer for the user timeout feature

Within my Jquery function, I have implemented a feature that darkens the screen after a period of user inactivity. This triggers a pop-up window giving the user the option to stay logged in by clicking a button. If there is no response within the set time ...

Using Jest and Typescript to mock a constant within a function

Just getting started with Jest and have a question: Let's say I have a function that includes a const set to a specific type (newArtist): export class myTestClass { async map(document: string) { const artist: newArtist = document.metadat ...

how can a select dropdown be dynamically displayed based on the previous selection?

If the first dropdown is set to "Professor" I want to display a second dropdown, but if it is set to "Student" then I do not want to display the second dropdown. function checkPrivilege() { var privilege = document.getElementById("permisija5").value; ...

The process of dynamically inserting input types into a <td> element using the innerHTML tag is not functioning properly in Internet Explorer

I am facing an issue with dynamically placing input types within a <td> tag - the innerHTML() method is not functioning properly in Internet Explorer, although it works fine in Mozilla. This is how I am inserting the input types using JavaScript, wi ...

Rearranging components in React does not automatically prompt a re-render of the page

I'm currently working on a project to display the update status of my Heroku apps. The issue I encountered was that the parent component (Herokus) was determining the order, but I wanted them sorted based on their update dates starting from the most r ...

Is it possible to utilize an enum for typing an array variable?

Is there a way to use an enum to define the valid types that an array can contain? I have been unable to find a solution so far, and I am curious if it is feasible. Below is the example code I have tried: interface User { name: string; } interface Ad ...

Troubleshooting Ng Serve Module Conflict

My latest project involved creating a chatbot system. However, whenever I try to open the system, an error pops up on the command prompt. I attempted to troubleshoot by uninstalling and reinstalling npm, but the issue persists. Below is a link to an image ...

Objective: Remove all soft items from array stored in MongoDb using Mongoose

I have a unique Array property in my document that is filled with lovely fluffy objects. Now, I am looking to remove all objects within a specific range -> qdate:20210225. The property in the database is named weeks and appears as follows: [ { ...

Designing a platform for dynamic components in react-native - the ultimate wrapper for all elements

export interface IWEProps { accessibilityLabel: string; onPress?: ((status: string | undefined) => void) | undefined; localePrefix: string; children: JSX.Element[]; style: IWEStyle; type?: string; } class WrappingElement extends React.Pure ...

The enigma of the mysterious karma provider error

As a newcomer to unit testing in JavaScript, AngularJS, and Karma, I have successfully written passing tests for controllers. However, when trying to test services, I encountered an error: Unknown provider <- nProvider <- User. The User service is th ...

How can data be displayed in AngularJS/Json without using ng-repeat?

It seems like I am required to use ng-repeat in order to display the data, but I would prefer to avoid using it. angular: App.controller('aboutLongCtrl', function ($scope, $http) { $http.get('test_data/ar_org.json') .then(func ...

Designing templates for websites and applications using node.js

Simplified Question: As I delve into improving my skills with node.js, I'm exploring the concept of templating. How would using node to serve one HTML file and loading page-specific information through AJAX/sockets impact performance and design princ ...