Substitute a unique section of a JSON data``

I am working with a JSON object named users, which looks like this:

[{"givenName":"helen","sn":"brown","phone":"44512","details":"512"},{{"givenName":"John","sn":"Doe","phone":"44600","details":"512"}]

To convert this JavaScript object to a JSON string, I use the JSON.stringify method. Then, I utilize the replace function to replace the value 512 with active. However, the issue is that this replacement affects all occurrences of 512 in the string. I specifically want to only apply this replacement on the values of the details key, not on the entire string content (for instance, I do not want to alter the phone value). How can I achieve this?

Answer №1

It's best to correct issues within a JSON object rather than trying to replace parts of it.

const arr = [{"givenName":"helen","sn":"brown","phone":"44512","details":"512"},{"givenName":"John","sn":"Doe","phone":"44600","details":"512"}];

for (const item of arr) {
  if (item.details === '512') {
    item.details = 'active';
  }
}
console.log(JSON.stringify(arr));

Answer №2

let userList = [{"givenName":"mary","sn":"jones","phone":"44599","details":"512"},{"givenName":"Jane","sn":"Smith","phone":"44622","details":"513"}]

We will now apply array.map()

const modifiedList = userList.map(item => {
    return {...item, details: item.details == 512 ? "active" : item.details};
});

Answer №3

If you're looking to specifically update the text within the details property without converting the entire object into a string, you can achieve this by iterating over the array using the Array.map() method and then replacing the value of the details property based on a regex pattern.

Give this a shot :

const jsonObj = [{
  "givenName": "helen",
  "sn": "brown",
  "phone": "44512",
  "details": "512"
}, {
  "givenName": "John",
  "sn": "Doe",
  "phone": "44600",
  "details": "512"
}];

const res = jsonObj.map(obj => {
    obj.details = obj.details.replace(/512/g, 'active');
  return obj;
});

console.log(res);

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

What is the best way to retrieve a ReactElement from the DOM?

Imagine I have a ReactElement displayed on the screen: <div id="container" data-reactid='reactid.2'></div> To access the HTMLElement, you can use the following code: var element = document.getElementById('container'); ele ...

"Encountering a blank page in React Router when transitioning between separate projects

I've come across some discussions about a similar issue like this one, but I haven't been able to resolve my problem. In my initial project, I can smoothly navigate between its pages. However, when I created a second project hosted in a subdirec ...

There was a problem accessing the website

Recently, I tried to access a web page from the server using command prompt by following a tutorial on YouTube. However, I encountered an error message while trying to open the page. The specific error is displayed below. Can someone please guide me on res ...

Golang decodes JSON using static typing rather than dynamic typing

I used to believe that json.Marshal utilized reflection to examine the passed type and then decoded it accordingly. However, I encountered an issue when I had a variable with a static type of any which actually stored a struct, and when passed to json.Unma ...

Ways to eliminate toggle event in Angular

I've been doing a lot of research online, but all the solutions I find are using jquery. I'm still getting the hang of Angular and Typescript. I found this and this to be unhelpful. I built a monthpicker from scratch, which has a simple and clear ...

Typescript does not produce unused members

Having an issue with the JS code that TypeScript compiler is generating. Here's an example class: // Class export class UserDTO { Id: number; FirstName: string; LastName: string; DateOfBirth: Date; getFullName(): string { ...

Ways to simultaneously install numerous gulp packages using node-package-manager

Recently, I made the transition to using the gulp task runner for automating my workflow. However, whenever I start a new project, I find myself having to install all the required packages listed in the gulpfile.js by running the following command: npm in ...

"Bringing back the page zoom/scale with the click of a button

I've hit a roadblock as I search for code to tackle my issue. Despite scouring Google and Stackoverflow extensively, I haven't come across anything that addresses my specific problem. Essentially, I have a button on my webpage labeled "Restore s ...

Decoding JSON data in Dart

I'm currently attempting to convert JSON data into an object in Dart. The documentation recommends using the Map type for parsing a JSON response. In reference to their guide on Using Dart with JSON Web Services: Parsing JSON, I found the following e ...

Got a not-a-number (NaN) value for the `children` prop in a

Just starting out with React and working on a type racer app. I've encountered an issue while trying to calculate WPM (Words per minute) - the calculation keeps returning 'NaN'. I've double-checked all the variables and ensured there ar ...

Issue with uploading media on Wordpress: "Unfortunately, an error occurred during the upload process. Please attempt again at a later time."

Often times, when trying to upload media from the front-end, I encounter this issue: An error occurred during the upload process It seems like the error occurs sporadically, making it even more challenging to troubleshoot. Sometimes, when logging in fo ...

What factors determine when Angular automatically triggers a setTimeout function compared to another?

Sorry if this all seems a bit odd, but I'll do my best to explain the situation. We have been given access to a small service that provides a simple form UI which we collect results from using an event. We've successfully implemented this in two ...

Switching between vertical and horizontal div layouts while reorganizing text fields within the top div

function toggleDivs() { var container = document.querySelector(".container"); var top = document.querySelector(".top"); var bottom = document.querySelector(".bottom"); if (container.style.flexDirection === "column") { container.style.flexDirec ...

What is the best way to retrieve JSON data using JavaScript within a loop?

I'm struggling to retrieve data from a JSON object. Here's the JSON structure I'm working with: var data = [ {"mes":{ "January":{ "Inversion":"1000","Fans":"1020"} ...

Guide on deleting objects based on their IDs when the IDs are stored in a separate array using JavaScript

I have two separate arrays. One array contains only integers as IDs (from a searchBox) and the other array contains objects, such as: categories = [1, 2, 5, 8]; items = [ { title: 'Hello', description: 'any description you want', cat ...

Please replace the text with only letters and then submit it without any spaces, periods, commas, or other symbols

Whenever I encounter a form like this, I need to submit it and replace the text in the name field with only letters - no commas, spaces, or special characters. https://i.sstatic.net/9FQnT.png myform.html <script> function fixInput(event) { na ...

Can markers be positioned on top of scroll bars?

Looking for a way to display small markers on the scrollbar of an overflow: scroll element, similar to features found in IDEs and text editors like this one: https://github.com/surdu/scroll-marker. I've considered using a pointer-events: none overlay ...

Encountering a TypeScript error when attempting to utilize indexOf on a Typed Array, leading to restriction

I have been working with an Interface, where I created an array of type Interface. I am currently facing some IDE error complaints when trying to use the .indexOf method on the Array. These errors seem confusing to me, and I'm hoping someone here migh ...

React hitting recursion limit due to excessive shouldComponentUpdate checks

I'm currently developing a real-time updating dashboard using React. The data for the dashboard components is fetched via an Ajax call and then passed to each component successfully. However, I encountered an issue with one specific component that re ...

Slide the next section over the current section using full-page JavaScript

I'm currently developing a website utilizing the FullPage.JS script found at this link . My goal is to have the next section slide over the previous one, similar to what is demonstrated in this example. I've attempted setting the position to fix ...