Setting a value to an empty string in Typescript

In the process of sorting and grouping data by the first word separated by an underscore (_), the expected result is to have 3 groups (e.g. orders, items and ""). Is there a way to assign a specific value (e.g. Others) to the empty string group? Check out this StackBlitz link for reference.

let rawData = [
  { name : 'orders_list', id : 10},
  { name : 'orders_price', id : 7},
  { name : 'items_list', id : 12 },
  { name : 'items_price', id : 7},
  { name : 'others-list', id : 7},
  { name : 'secondOthers-list', id : 7},
]

let data = rawData.reduce((r, e) => {

  let group = e.name.substr(0, e.name.indexOf('_'));

  if(!r[group]) {
    r[group] = {group, children: [e]}
  } else {
    r[group].children.push(e);
  }

  return r;
}, {})

let result = Object.values(data)

console.log(result)

Answer №1

Check out this functional stackblitz that I put together :)

// Including stylesheets
import './style.css';

// TypeScript code ahead!
const appElement: HTMLElement = document.getElementById('app');
appElement.innerHTML = `<h1>TypeScript Starter</h1>`;

let rawData = [
  { name : 'orders_list', id : 10},
  { name : 'orders_price', id : 7},
  { name : 'items_list', id : 12 },
  { name : 'items_price', id : 7},
  { name : 'others-list', id : 7},
  { name : 'secondOthers-list', id : 7},
]


let data = rawData.reduce((r, e) => {

  let group = e.name.substr(0, e.name.indexOf('_'));

  if(!r[group]) {
    r[group] = {group, children: [e]}
  } else {
    r[group].children.push(e);
  }

  return r;
}, {})

// As data is an object at this point, to convert it to an array of values
// we utilize the Object.values method
let result = Object.values(data)
var resultMap = result.map(_val => {
  return _val.group
})
var index = resultMap.indexOf('')
result[index].group = 'Others'

console.log(result)

https://stackblitz.com/edit/typescript-6xfk3j

Answer №2

Take a look at this code snippet.

// Include CSS styles
import './style.css';

// Start writing TypeScript code!
const appElement: HTMLElement = document.getElementById('app');
appElement.innerHTML = `<h1>TypeScript Starter</h1>`;

let rawData = [
  { name : 'orders_list', id : 10},
  { name : 'orders_price', id : 7},
  { name : 'items_list', id : 12 },
  { name : 'items_price', id : 7},
  { name : 'others-list', id : 7},
  { name : 'secondOthers-list', id : 7},
]


let data = rawData.reduce((result, element) =>{
  let group = element.name.substr(0, element.name.indexOf('_'));

  if(!result[group]) {
    result[group] = {group, children: [element]}
  } else {
    result[group].children.push(element);
  }

  return result;
}, {})

// Convert object data to an array of values using Object.values method
let transformedData = Object.values(data)
transformedData.filter(item =>{
  if(item.group==''){
    item.group='Others'
  }
});

console.log(transformedData)

Check out the Code on StackBlitz : https://stackblitz.com/edit/typescript-pe8k9p

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

Having trouble getting ng-click to function properly in TypeScript

I've been struggling to execute a function within a click function on my HTML page. I have added all the TypeScript definition files from NuGet, but something seems to be going wrong as my Click Function is not functioning properly. Strangely, there a ...

Examining the potential of a promise within a dynamic import feature in Angular

Here's a code snippet that I'm working with: The component file (component.ts) looks like this: async ngOnInit() { import('dom-to-image').then(module => { const domToImage = module.default; const node = document.getEl ...

Encountering issues with the dependency tree while trying to install npm packages

I'm encountering an exception while attempting to install npm packages using the npm i command. The error message is displayed in this link: https://i.sstatic.net/x8N3W.png Despite trying to reinstall Node.js and turning off the proxy with these com ...

Utilizing custom types in React with TypeScript and Prop-Types

Currently, I am working with a string type literal that looks like this: type MyType = 'str1' | 'str2' | 'str3'. I need one of my props to only accept this specific type, but I'm struggling to specify this in PropTypes. ...

Unable to integrate the leaflet-realtime plugin with Angular5 and Ionic at this time

Having trouble utilizing the leaflet-realtime plugin in my Ionic3 & Angular 5 project When I import import leaflet from 'leaflet'; in this manner Upon attempting to implement real-time functionality with the following code snippet leaflet ...

Navigating to the next page on a dynamic component in Angular 5 by

I'm uncertain if this scenario is feasible, but I have a page that fetches a list of items from an external API. There are currently 5 elements on the page, each acting as a link to its individual dynamically generated page through query strings. For ...

The in-memory-web-api is failing to respond to queries when using Chrome

I've been experiencing an issue with my in-memory database setup. Even though I have registered everything correctly, I am not receiving any data back. There are no errors or 404 responses; it seems like the app is intercepting the request and returni ...

how does an SPA handle HTTP requests when the route is modified?

Picture this scenario: a request is in the process of loading when the page or component suddenly changes. What happens to that loading request? Take into account that this situation arises when working with front-End SPA (single page application) like pr ...

Guide on moving from tab 2 to tab 1 by clicking the device's back button in Ionic 3

I have been following the documentation at https://ionicframework.com/docs/components/#tabs Upon logging in, I use the key this.navCtrl.setRoot("tabs"); to navigate to the next page, where the home tab or Tab1 is automatically selected. In total, I have ...

Adding types to computed properties in Vue 3's Composition API is a seamless process

Having an issue where I am trying to add type to computed but keep encountering this error: Overload 1 of 2, '(getter: ComputedGetter<AuthFormType>, debugOptions?: DebuggerOptions | undefined): ComputedRef<AuthFormType>', gave the fol ...

"Encountered an issue with Angular 2 when attempting to post data to an API -

After downloading a project from the link provided by ASP.NET on individual accounts in Web API, I managed to run it successfully on VS2015 and IIS Express. However, my goal now is to utilize Angular 2 to call the API. In order to achieve this, I set up a ...

The issue with Angular2 ng bootstrap datepicker minDate functionality defect

Error message when using ng bootstrap with minDate: "minDate value must be or return a formatted date" HTML Component: <div class="input-group"> <input class="form-control" name="date_of_birth" type="text" ngbDatepicker #d="ngbDatepicker" id ...

Execute --runTestsByPath on two or more distinct paths

Currently, I am utilizing the jest cli for running my tests. Jest offers a useful cli option known as --runTestsByPath, which allows me to specify the locations of my tests. Despite having unit tests spread out in various directories within my repository, ...

Unassigned variable in need of initialization within Angular 2

There seems to be an issue with the two-way data binding not functioning correctly. I am trying to retrieve the data using {user | json}, but I encounter an error when using [(ngModel)] = "user.username". Data Model export interface UserModel { ...

Adding css-element-queries to an angular 6 project

I am currently attempting to install and utilize the css-element-queries library. To install, I executed the following command: npm i css-element-queries Following that, I attempted to import the ResizeSensor class from the library in this manner: impo ...

Compile the sources of an npm dependency using Brunch

Recently, I've been facing an issue while trying to develop my web application using Brunch. The problem arises from a specific npm package called animated-vue, which consists of sources programmed in ES2016. After adding this package as a dependency ...

Could this be the expected outcome of custom error handling?

I'm currently revamping the maze package that was created five years ago using ES2015. As part of this update, I am implementing a custom error handling feature called LengthError. This error will be triggered if an argument of type Function does not ...

Combining Vue-Test-Utils with TypeScript typings for wrapper.vm

So, I ran into an interesting situation. Has anyone ever worked with typescript + vue-test-utils and attempted to change a value for testing purposes like this: wrapper.vm.aCoolRefValueToManipulate = 'something much cooler'? I gave it a shot, a ...

Tips for streamlining interface initialization and adding items to it

I have designed an interface that includes another interface: export interface Parent { children: Child[]; } export interface Child { identifier: string; data: string; } Is there a more efficient way to initialize and add items to the array? Curren ...

Testing the derived class resulted in failure with the error message: "Unable to resolve all parameters for : (?, ?) in Angular 5."

Encountering an issue when trying to run Karma on a structure consisting of an abstract class, a derived class, and a test. The error message that is being thrown is: Failed: Can't resolve all parameters for ActivationsComponent: (?, ?). The abstrac ...