Eliminate consecutive duplicate numbers in a JSON object using JavaScript

Here is the json data:

{ "question_1": 
  { "type"  : "string"
  , "title" : "What did he want to make for dinner?"
  , "enum": 
    [ " a.) He wanted to make some salad and spaghetti"
    , " b.) He wanted to make some pasta salad"
    ] 
  , "required": false
  } 
, "question_2": 
  { "type": "string"
  , "title": "Did he have the ingredients to make dinner?"
  , "enum": 
    [ " a.) Yes, he had the ingredients"
    , " b.) No, he didn't have the ingredients"
    ] 
  , "required": false
  } 
, "question_3": 
  { "type"  : "string"
  , "title" : "Where did he go shopping?"
  , "enum": 
    [ " a.) He went to Albertsons"
    , " b.) He went to Albertos"
    ] 
  , "required": false
  } 
}

Looking at my json, I noticed that there are repeated numbers next to each other in the question titles.

For example:

1. 1. => 1.
2. 2. => 2.
3. 3. => 3.

I am seeking a solution to eliminate this repetition.

Is there a way to remove duplicate numbers next to each other within the json?

Answer №1

One way to update it is by using a regex. By utilizing grouping references with parentheses like (\d), you can create a group containing one decimal, allowing you to preserve numbers such as "1. 2." and reference them in the replacement process with \1:

const data =
  { "question_1": 
    { "type"  : "string"
    , "title" : "1. What did he want to make for dinner?"
    , "enum": 
      [ " a.) He wanted to make some salad and spaghetti"
      , " b.) He wanted to make some pasta salad"
      ] 
    , "required": false
    } 
  , "question_2": 
    { "type": "string"
    , "title": "2. Did he have the ingredients to make dinner?"
    , "enum": 
      [ " a.) Yes, he had the ingredients"
      , " b.) No, he didn't have the ingredients"
      ] 
    , "required": false
    } 
  , "question_3": 
    { "type"  : "string"
    , "title" : "3. Where did he go shopping?"
    , "enum": 
      [ " a.) He went to Albertsons"
      , " b.) He went to Albertos"
      ] 
    , "required": false
    } 
  };

Object.values(data).forEach(v => v.title = v.title.replace(/(\d)\. \1\./, '$1.'))
console.log(Object.values(data).map(v => v.title))

Answer №2

If you are working with JSON data and planning to use the JSON.parse method, there is an interesting feature you can utilize known as the optional reviver parameter.

Reviving Values

When a function is passed as the reviver, it specifies how each parsed value should be transformed before being returned. If a non-callable value is encountered, it will be ignored. The function receives two arguments:

Key

The key associated with the value being processed.

Value

The parsed value that needs transformation.

const jsonData = `{
  "question_1": {
    "type": "string",
    "title" : "1. 1. What did he want to make for dinner?"
  },
  "question_2": {
    "type": "string",
    "title": "2. 2. Did he have the ingredients to make dinner?"
  } 
}`;

console.log(
  JSON.parse(jsonData, (key, value) => typeof value === 'string' ? value.replace(/(\d)\. \1\./, '$1.') : value)
)

Building upon Moritz Ringler's approach.

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

Binding data from a JSON response to a listbox

I am a beginner in XAML and may need some time to learn, so please bear with me. Here is my C# code where I am attempting to bind the "attributes" to a listbox. public DirectionPage() { InitializeComponent(); List<Feature> feat ...

Parse the text data and transform the parsed data into JSON format

My task involves processing a string variable msg.payload, which contains the following information. Hi Team, Below are the details of for the given source platform. name=abc status=Active company=Discovery FromDate=6/05/2020 ToDate=20/05/2020 Please do t ...

Ways to include ajax information in the attribute of a td component

Within my ajax datatable initialization, I currently have the following setup: "ajax": { "url": "{{ route('cust_continfo_data_table') }}", "dataType": "json", "type": "POST", "data": { _token: "{{ csrf_token() }}", ...

Using raycasting in Three.js to select objects and adding animation

In my current project, I have found that raycasting selection works perfectly fine for static meshes. However, when it comes to animated meshes, I have encountered an issue where the ray selection does not take into account the movement of the mesh. Instea ...

How can I retrieve the width of HTML content without referring to the width of the window?

Is there a way to determine the total width of the HTML content, including what is visible and what is hidden due to vertical scrolling when the window size is reduced and a scrollbar appears? ...

Tips for organizing and styling data in SQL queries with PostgreSQL

I have a table named: locations columns => location, ltn, lgn Data in the table: Banguluru, 22,24, Banguluru, 22,25 Banguluru, 22,26 Hyderabad, 22,27 I am looking for an output structured like this: { location: 'Hyderabad', p ...

Field Enchanted - JQuery Plugin

A TypeError was caught: Object #<Object> does not contain the method 'easeOutCubic' is being output in the console, and it seems to be related to a JQuery plugin known as Decorated Field. Upon inspecting the contents of the zip file, I cou ...

Combine identical arrays of object keys into one unified array

https://i.sstatic.net/A2r5c.png I am striving for this particular output [ productId:106290, productserialno:[{ "12121", "212121" }] ] ...

Utilizing Javascript to have each line displayed with separate returns upon form submission

How can I make each link unique when placed on separate lines? Line 1 = <a href="LINE 1 CONTENTS" target="_blank">Link - 01</a> Line 2 = <a href="LINE 2 CONTENTS" target="_blank">Link - 02</a> Line 3 = <a href="LINE 3 CO ...

Using a dojo widget within a react component: A beginner's guide

Has anyone found a way to integrate components/widgets from another library into a react component successfully? For example: export default function App() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + ...

Dirty context detected in Material-UI TextField

Trying to understand how to check for dirtyness with material-ui's FormControl or TextField component. The TextField demo page mentions that TextField is made up of smaller components (FormControl, InputLabel, Input, and FormHelperText) which can be c ...

Saving information retrieved from queries using Mongoose and Node.js into variables for later use

I have some code located in app.js. var Song = db.model('Song'); var Album = db.model('Album'); My goal is to render the data to index.jade using two variables: a list of songs and a list of albums. I am querying the data l ...

Show the present time pulled from the timer

I am in possession of a countdown timer that starts at zero and counts up to 100. The timer displays the count in a p tag with the ID of countdowntimer. I am attempting to show the current time when I click a button while the timer is running. Additional ...

Troubleshooting ASP.net core AntiForgeryToken problem: model not receiving bound data

Currently, I have a functioning project built on a booking system in asp.net core that integrates a google Timeline chart. The interactive element involves a modal popup, which displays a partial view for data input when the chart is clicked. Utilizing Jav ...

Exploring TypeScript's type discrimination with objects

When working with TypeScript, type discrimination is a powerful concept: https://www.typescriptlang.org/play#example/discriminate-types But is it possible to achieve something like this? type A = {id: "a", value: boolean}; type B = {id: "b ...

What is the best method for establishing a dictionary index key prior to iterating over data in order to retrieve both the

Having a hard time parsing JSON data and setting a dict[index] due to the index variable being found only once in the JSON while the rest of the key-values require a loop for extraction. I attempted a nested loop but encountered an error: TypeError: list i ...

Scope loss occurs when AngularJS button is clicked

I am encountering a scope problem with a button on my webpage. The page contains a ui-grid, and when the "Add New" button is clicked, it hides the grid and displays a div where users can input a new record. After saving the information and returning to the ...

Refine the pandas Dataframe with a filter on a JavaScript-enabled website

I recently inherited a large software project using Python/Flask on the backend and HTML/Javascript on the frontend. I'm now looking to add some interactivity to one of the websites. I have successfully passed a dataframe to the webpage and can displa ...

Retrieving information from JSON results in an undefined output

I'm currently working on extracting a specific value from the data I receive from a server. The data is stored in a variable named body. Here's what I have attempted: console.log(body); console.log(body._id); console.log(body["_id"]); And this ...

Can CSS actually generate accurate inches?

Can you accurately set the width of an element, like a div, in inches and expect it to maintain that width across different devices? Or will it simply scale at a ratio like 1in = 96px? Edit: Try using CSS to set an element's width in inches and then ...