A method for dividing a string into separate characters and organizing them into an array of JSON objects

I have a collection of JSON objects with a fixed key 'type' and additional keys based on the type. Here is an example of how it looks:

theArray = [
    {
        "type": "text",
        "text": "= SUM("
    },
    {
        "type": "formula",
        "attrs": {
            "id": 20,
            "data": "Cost",
        }
    },
    {
        "type": "text",
        "text": ",,"
    }
]

After filtering all items where 'type': 'text' like this:

this.theArray.filter(a=>a.type === 'text'))

I am aiming to split each object where type === 'text' so that every character in the text key becomes an item in this.theArray.

Thus, I want to split the above 'type': 'text' object as follows:

theArray = [
   {
       "type": "text",
       "text": "="
   },
   {
       "type": "text",
       "text": " "
   },
   {
       "type": "text",
       "text": "S"
   },
   {
       "type": "text",
       "text": "U"
   },
   {
       "type": "text",
       "text": "M"
   },
   {
       "type": "formula",
       "attrs": {
           "id": 20,
           "data": "Cost",
       }
   },
   {
       "type": "text",
       "text": ","
   },
   {
       "type": "text",
       "text": ","
   },
]

The first 'type': 'text' object should be split character by character, adding each symbol (such as =, S, U, M) as a new array item with 'type': 'text' and text: that specific character.

I am aware that splitting a string separately requires using .split('')

However, my current approach does not work (only getting the original '= SUM(' object), and I'm uncertain how to proceed further. Does anyone know how to adjust the initial array to match the desired format?

if(theArray.filter(a=>a.type === 'text')) {
    theArray.map(a=>a.text).forEach(element => {
        element.split('')
        theArray.push({type:"text", text: element})
    })
}

Answer №1

If you want to create an array of new objects for the "text" objects and flatten them out in the return, you can use the flatMap() method. This example utilizes the spread syntax (...) to split the strings into an array of characters before mapping them to individual objects.

const theArray = [
  {
    "type": "text",
    "text": "= SUM("
  },
  {
    "type": "formula",
    "attrs": {
      "id": 20,
      "data": "Cost",
    }
  },
  {
    "type": "text",
    "text": ",,"
  }
]

const result = theArray.flatMap(o => {
  if (o.type === 'text') {
    return [...o.text].map(char => ({ type: o.type, text: char }));
  }
  return o;
})

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

Answer №2

To simplify the mapping process, you can use a single map function with a conditional statement to handle elements of type 'text' specifically:

const theArray = [
    {
        "type": "text",
        "text": "= SUM("
    },
    {
        "type": "formula",
        "attrs": {
            "id": 20,
            "data": "Cost",
        }
    },
    {
        "type": "text",
        "text": ",,"
    }
]

console.log(
    theArray
      .flatMap((el) => el.type === 'text' ? el.text.split('').map((char) => ({ type: 'text', text: char })) : el)
)

Answer №3

Utilize the power of flatMap in this scenario

Get it done in just one line of code

const result = theArray.flatMap((o) =>
  o.type === "text"
    ? o.text.split("").map((s) => ({ type: o.type, text: s }))
    : o
);

const theArray = [
  {
    type: "text",
    text: "= SUM(",
  },
  {
    type: "formula",
    attrs: {
      id: 20,
      data: "Cost",
    },
  },
  {
    type: "text",
    text: ",,",
  },
];

const result = theArray.flatMap((o) => {
  if (o.type === "text") {
    return o.text.split("").map((s) => ({ type: o.type, text: s }));
  }

  return o;
});
console.log(result);

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

Loading vue.config.js Asynchronously for Pre-Rendering Meta Data

I am facing an issue with asynchronously loading data in my Vue.js application's config for use with Chris Fritz's PrerenderSPA webpack plugin. It seems that the routes are not being pre-rendered as expected. When I manually input the values, th ...

Checking the formik field with an array of objects through Yup for validation

Here is a snippet of the code I'm working on: https://codesandbox.io/s/busy-bose-4qhoh?file=/src/App.tsx I am currently in the process of creating a form that will accept an array of objects called Criterion, which are of a specific type: export inte ...

Reactjs is retrieving several items with just one click on individual items

I am having trouble getting only a single sub-category to display. Currently, when I click on a single category, all related sub-categories are showing up. For example, in the screenshot provided, under the Electronic category, there are two subcategories: ...

"Splitting a DOMNodeList into an array of chunks using PHP

I am attempting to utilize an array chunk function with a DOMNodeList. Unfortunately, this is resulting in an error message as the DOMNodeList does not conform to the standard PHP array format. Below is the code snippet causing the issue: foreach (array_c ...

Unable to designate decimal value as the default in DropdownListFor in ASP.NET Core when utilizing JavaScript

Everything appears to be functioning properly, except when dealing with decimal values in the following code snippet: $('select#listspec_0__qty option[value = 105.3]').attr("selected", true); ...

Reproducing a table row

Here is the table structure I am working with: <table id="customFields" class="table table-bordered table-hover additionalMargin alignment"> <thead> <tr> <th colspan="2"></th> <th>Some Title</ ...

Error during live-server npm installation: symlink issue persists even with root/admin privileges

In my current project, I am following a tutorial on AngularJS from the book titled "Unraveling AngularJS 1.5 (With Over 130 Complete Samples" by István Novák, which stipulates the need for installation of Node.js. The appendix of this book provides comma ...

Learn how to utilize JavaScript produced by the `webpack output library` in a `nodejs` application

I'm currently utilizing webpack to bundle my JavaScript into a library that serves two purposes: one for browser usage and the other for integration into Node.js applications. Below is a snippet of my webpack configuration: output: { filename: ...

Altering the dimensions of a <div> based on the retrieved data

I am currently retrieving data from an API and displaying certain properties using mapping. I would like to adjust the width of the component based on the value of these properties. <h5> <span className="viewcount" ref={boxSize}> ...

Error message: "Unable to locate jQuery file within the node.js + Express application running on Heroku platform."

My current setup involves a node.js application with Express and express-handlebars deployed on Heroku. However, whenever I run the app, the console displays a 404 error for the jquery file, leading to subsequent failures for dependent libraries like Boots ...

The error message "Type 'Observable<void>' cannot be assigned to type 'void | Action | Observable<Action>' when integrating an effect" is displayed

Encountering an error when trying to add effects using the 'run' method. Attempted to manually return a string, number, and other types, but nothing seems to work. Here is the effects code snippet: @Effect() getRoles$: Observable<Roles[]> ...

Getting the width of an element using a React ref is a helpful technique that allows you

I am struggling to retrieve the width of a select field using React Ref. this.selectRef.current is returning an object, but I can't seem to find a way to access the width of the element. <Select fullWidth ref={this.selectRe ...

Adjust the stroke and fill colors of an SVG element when hovering over it

I am facing a challenge with an SVG image that I have: https://i.stack.imgur.com/r4XaX.png When hovered over or clicked, it should change to https://i.stack.imgur.com/EHRG2.png Current Icon <svg width="24" height="24" viewBox="0 0 24 24" fill="non ...

Is it possible to manually trigger a version change transaction in IndexedDB?

I have been working on a Chrome extension that uses the IndexedDB to store data client-side in an IDBObjectStore within an IDBDatabase. The data structure requires users to be able to modify the object store freely, such as adding new objects or modifying ...

Global jQuery variables are unexpectedly coming back as "undefined" despite being declared globally

I need to save a value from a JSON object in a global variable for future use in my code. Despite trying to declare the country variable as global, it seems like it doesn't actually work. $.getJSON(reverseGeoRequestURL, function(reverseGeoResult){ ...

Process JSON data from an input using Javascript

I am encountering an obstacle at the final step of my data flow process. Currently, I am in the midst of developing an application that retrieves input from an HTML form field and utilizes Ajax to fetch data relevant to the user's input. Allow me to e ...

Security Measures for Parsing Arrays using eval() Function

When I receive a string of an array containing objects via an http request, I use eval() to parse it. Since I am expecting an array object after parsing, how can I secure this eval() process beyond using if (Array.isArray(parsedObj)) ... Is there a bette ...

Node.js - Issue with res.json function: inconsistency across different routes

Currently working with the MERN stack (Mongo, Express, React, Node) and encountering an issue in my API. Here is a snippet from my plaid.js file where one of my routes is causing an error. I have omitted any sensitive information such as secret tokens, bu ...

Creating a Validation Form using either PHP or JavaScript

I need to create a form with the following columns: fullname, email, mobile, and address. If the visitor fills out the mobile field, they should only be allowed to enter numbers. And if the visitor fills out the email field, they should only be allowed to ...

Can JavaScript be used to identify if the current browser is the default one being used?

It would be incredibly helpful for my application to determine if the current browser is set as the default browser. Is it feasible, utilizing JavaScript, to ascertain whether the browser in which my page is open is the default browser (i.e. the browser t ...