Creating a merged object from a split string array in TypeScript

I possess an array containing objects structured as follows;

const arr1 = [
  {"name": "System.Level" },
  {"name": "System.Status" },
  {"name": "System.Status:*" },
  {"name": "System.Status:Rejected" },
  {"name": "System.Status:Updated" }
]

My objective is to separate the name property and construct an object. Ultimately, I aim to form an object like this;

{
  "System.Level": true,
  "System.Status": {
    "*": true,
    "Rejected": true,
    "Updated": true
  }
}

This is what I have accomplished so far;

transform(element){
  const transformed = element.split(/:/).reduce((previousValue, currentValue) => {
    previousValue[currentValue] = true;
  }, {});
  console.log(transofrmed);
 }

const transofrmed = arr1.foreEach(element => this.transform(element));

The current output is;

{System.Level: true}
{System.Status: true} 
{System.Status: true, *: true}
{System.Status: true, Rejected: true}
{System.Status: true, Updated: true}

It's very close to my desired outcome but I need to merge and assign a key. How can I utilize the first value as a key in the reduce method? Is it feasible to merge objects with the same key?

Answer №1

To simplify the keys that are split, you can check if the last level has been reached. If it has, then assign a value of true; otherwise, use an existing object or create a new one.

const
    array = [{ name: "System.Level" }, { name: "System.Status" }, { name: "System.Status:*" }, { name: "System.Status:Rejected" }, { name: "System.Status:Updated" }],
    object = array.reduce((r, { name }) => {
        var path = name.split(':');
            last = path.pop();
        path.reduce((o, k) => o[k] = typeof o[k] === 'object' ? o[k] : {}, r)[last] = true;
        return r;
    }, {});
    
console.log(object);

Answer №2

Utilize the Array.reduce() method on the list of properties. Split the path by : and check for a second part. If there is a second part, assign it to an object using object spread to ensure that undefined or true values are ignored while adding object properties. If no second part exists, set the value to true:

const array = [{ name: "System.Level" }, { name: "System.Status" }, { name: "System.Status:*" }, { name: "System.Status:Rejected" }, { name: "System.Status:Updated" }];

const createObject = (arr) => 
  arr.reduce((r, { name }) => {
    const [first, second] = name.split(':');
    
    r[first] = second ? { ...r[first], [second]: true } : true;
    
    return r;
  }, {});
    
console.log(createObject(array));

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

Issue with Angular2/4 Module: Unable to locate 'three' in the application directory

As a newcomer to Angular and TypeScript, I am encountering difficulties when trying to import the @types/three npm package. I have created a new Angular project and attempted to use the three package, but I keep receiving the following error: Module not f ...

A guide to securely retrieving data from the Hono API endpoint using type safety within a Next.js application

Currently, I am using Hono as my API endpoint with Bun. Now, I am working on a new app with Next.js and I want to ensure type safety when fetching data from my API. I believe I can accomplish this through RPC. However, I am unable to locate AppType mention ...

Tips on connecting data within a jQuery element to a table of data

I am currently developing a program that involves searching the source code to list out element names and their corresponding IDs. Instead of displaying this information in alert popups, I would like to present it neatly within a data table. <script> ...

Utilizing turbolinks enables the page to be reloaded upon form submission

Currently, I have implemented turbolinks in my Rails application. However, every time I submit a form, the page reloads and the form is submitted. Is there a way to prevent the page from reloading and also submit the form seamlessly? ...

typescript warns that an object may be potentially null

interface IRoleAddProps { roles: Array<IRole> } interface IRoleAddState { current: IRole | null } class RoleAdd extends React.Component<IRoleAddProps, IRoleAddState> { state = { current: null, } renderNoneSelect = () ...

The 'canvas' module could not be located in the system.Here are the required stacks:- /var/task/index.js- /var/runtime/index.mjs

I am currently developing a lambda function using the serverless framework. The function utilizes chartjs-node-canvas to create graphics, and everything runs smoothly on my MacBook when tested locally. However, when I deploy the function to AWS either dire ...

Tips for deactivating dates in the jquery datepicker that correspond to entries in a MySQL database

Is there a way to disable dates directly from a MySQL database in jQuery Datepicker? It seems tedious to constantly update dates in JavaScript, so I'm exploring the option of storing future disable dates in the MySQL database and displaying them in th ...

Has the Soundcloud web widget API become obsolete?

I am currently working with the SoundCloud widget API (). My main goal is to retrieve information about the tracks within a set. Unfortunately, it seems like I am only able to utilize the methods widget.getSounds() and widget.getCurrentSound successfully ...

In JavaScript programming, the function is always executed after the bottom code

I am currently working on a piece of code that is partially functional. The purpose of this code is to verify the existence of an email address in a database. If the email does not exist, it should return true; $(document).ready(function() { var ema ...

Tips for implementing assertions within the syntax of destructuring?

How can I implement type assertion in destructuring with Typescript? type StringOrNumber = string | number const obj = { foo: 123 as StringOrNumber } const { foo } = obj I've been struggling to find a simple way to apply the number type assertio ...

How can I turn off strict null checks in TypeScript when using ESLint?

ESLint keeps flagging my object as potentially null despite having an if statement to check for it. const user: User | null = getUser() if (user) { // if (user !== null) doesn't work either await user.updateProfile({ di ...

Tracking user sessions using cookies, not relying on JavaScript like Google does

Currently, I am working in an environment that utilizes PHP on the server side and Javascript on the client side. In order to monitor user sessions, I regularly send a JS PUT request to the server every 5 seconds. This allows me to gather data such as the ...

Unexpected behavior observed with negated character: ? ^

I am looking to create a form where users can input their phone number and have the flexibility to choose how they want to separate the numbers. I have been using a regex pattern for validation: var regex = /[^0-9 \/-\\\(\)\+ ...

Options for importing TypeScript in WebStorm

Using WebStorm for auto-importing TypeScript classes has been a great help to tidy up my code and make it more organized. However, I have noticed that the imports are always formatted in a single line like this: import { Component, EventEmitter, Input, O ...

Capture a snapshot of a webpage that includes an embedded iframe

Currently, we have a nodeJS/angular 4 website that contains an iframe from a third party (powerBI Emebdded). Our goal is to develop a feature that allows the end user to capture a screenshot of the entire page, including the content within the iframe. We ...

What is the best way to redirect nodejs requests to a separate nodejs application?

Hello! I am currently working on a project to create an API gateway using Node.js and Express. The goal is to showcase a small-scale microservices architecture by routing requests to different microservices. For instance, if I have microservices A, B, and ...

Switch the ngClass on the appropriate ancestor element for the dropdown menu

Utilizing Angular CLI version 8.3.0, I aim to construct a sidebar featuring a drop-down menu. My objective is to apply the "open" class to toggle the opening of the drop-down section. However, the current challenge I am encountering is that when I click to ...

I encountered the "Unknown keystone list" error when I first began using the app on Keystone 4.0

I have implemented routes to post event data. var keystone = require('keystone'); var Event = keystone.list('Event'); module.exports = function (req, res) { if (!req.body.name || !req.body.startTime || !req.body.endTime) { retu ...

How to Dynamically Update Sass Styles with Webpack 2?

Currently, I am in the process of setting up a React application that utilizes Webpack2, webpack-dev-middleware, and HMR for the development phase. One peculiar issue that I have encountered is related to updating .scss files. When I make changes to my .sc ...

Remove properties that are not part of a specific Class

Is there a way to remove unnecessary properties from the Car class? class Car { wheels: number; model: string; } const obj = {wheels:4, model: 'foo', unwanted1: 'bar', unwantedn: 'kuk'}; const goodCar = filterUnwant ...