Modify the data in a JSON array and receive the revised array using JavaScript

Within my JSON object, I have price values in numerical format.

I am looking to convert these price values into strings within the same object

My approach involves using the map function:

var prods = [
  {
    "id": "id-1",
    "price": 239000,
    "info": "info-1"
  },

  {
    "id": "id-2",
    "price": 90770,
    "info": "info-2"
  },

  {
    "id": "id-3",
    "price": 200787868,
    "info": "info-3"
  },
];


prods.map(function(a) {
         a.price.toString()
        .replace(/(\d)(?=(\d{3})+(\D|$))/g, '$1 ');
})

Although I expect the map function to modify my prods object, it remains unchanged.

(Un)working JS Bin

I am curious about how to update the original object to meet my requirements.

Answer №1

Text values cannot be changed once set.

String#replace will provide a new string, necessitating an assignment.

If you are modifying just one attribute, Array#forEach may come in handy.

var items = [{ id: "id-1", cost: 239000, description: "description-1" }, { id: "id-2", cost: 90770, description: "description-2" }, { id: "id-3", cost: 200787868, description: "description-3" }];

items.forEach(function(item) {
    item.cost = item.cost.toString().replace(/(\d)(?=(\d{3})+(\D|$))/g, '$1 ');
});

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

Answer №2

Make sure to update the 'price' variable after performing the replacement

prods.map(function(a) {
         a.price = a.price.toString()
        .replace(/(\d)(?=(\d{3})+(\D|$))/g, '$1 ');
})

Answer №3

make sure to utilize this particular code

Example Script

items.map(function(item) {
             item.price = ""+item.price;
})

Answer №4

Keep in mind that the map function applies a specified function to each element in an array, creating a new array with the results. The original array remains unchanged, so you must assign the new array to a variable.

var products = [
  {
"id": "id-1",
"price": 239000,
"info": "info-1"
  },
  
  {
"id": "id-2",
"price": 90770,
"info": "info-2"
  },
  
  {
"id": "id-3",
"price": 200787868,
"info": "info-3"
  },
];


products = products.map(function(item) {
  item.price = item.price.toString()
   .replace(/(\d)(?=(\d{3})+(\D|$))/g, '$1 ');
  return item;
});
console.log(products);

Answer №5

To update the price, utilize the lambda function within the map function and create a new array to store the modified values.

let updatedArray = [];
prods.map(function(item) {
     item.price = item.price.toString()
    .replace(/(\d)(?=(\d{3})+(\D|$))/g, '$1 ');
     updatedArray.push(item);
})

This method ensures that your original array remains unchanged.

Test it on the Ramda REPL

Best wishes, Felix

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

Decoding a JSON array containing multiple JSON objects into an ArrayList of org.json.JSONObject instances using Gson

I have a JSON string that looks like this: { "r": [ { "pic": "1.jpg", "name": "Name1" }, { "pic": "2.jpg", "name": "Name2" }, { "pic": "3.jpg", "name": "Name3" } ] } My goal is to convert it ...

what is the mechanism behind __dirname in Node.js?

Node.js is a new technology for me and I recently discovered the "__dirname" feature which is really useful for obtaining the absolute path of the script. However, I am intrigued by how it works and how it manages to interpret the directory structure. De ...

Implementing restriction measures for deterring harmful conduct within ExpressJS

Recently, I was alerted to some potential vulnerabilities in the application I'm currently developing, particularly in relation to the JavaScript code on the front-end. These flaws could allow a user to exploit the system by clicking multiple buttons ...

Enhance click functionality on list item content using knockoutjs

Check out my app on GitHub or view it live at this link. I'm trying to implement a feature where clicking on each item, like "Bookworm Buddy," will toggle its description within the project. Here's what I've attempted so far: function AppV ...

Parsing JSON using Gson in which every field is treated as an object

I have a JSON structure like this: "fields": [ [ { "id": "11111" }, { "name": "dsfafds" }, { "description": "sdfadfas" } ], ] { "id": ...

Ways to divide different paths within a React Application

In my index.js file, I currently have the following code: <Router routes={routes} /> I want to move the routes section to a separate file. Here's what I've tried so far: routes.js export default ( <div> <Route path= ...

The relentless Livewire Event Listener in JavaScript keeps on running without pausing

I need to create a solution where JavaScript listens for an event emitted by Livewire and performs a specific action. Currently, the JavaScript code is able to listen to the Livewire event, but it keeps executing continuously instead of just once per event ...

Is it possible to set the state property in React js using the axios response?

After receiving data from axios, I am trying to store the response in a state value for rendering it in html. However, even though response.results displays the data when printed out, setting response.results in setState() results in an empty value. Here ...

Tutorial on how to update a specific value in an array of objects using setState on click event

I need to toggle the active class on click, setting it to a local state and changing all other objects in the state to inactive. const [jobType, setJobType] = useState([ { "class": "active", "type& ...

Guide to setting up a Cordova and TypeScript project using the command line interface

For my mobile application development, I rely on Cordova and execute cordova create MyApp in the command-line to initiate a new project. I am familiar with JavaScript but now require TypeScript for my project. Please assist me in setting up a Cordova pro ...

Revise for embedded frame contents

Is it possible to modify the HTML content of an iframe within a webpage? I currently have this code snippet: <iframe src="sample.html"></iframe> I am looking for a way to edit the contents of sample.html without directly altering the HTML co ...

Don't display div if database has certain value - Angular

Is there a way to determine if a specific value exists in a PostgreSQL database? If so, can I then hide an HTML element based on this information? Can CSS and JavaScript be used to hide elements, or is there another method that should be utilized for hidi ...

Showing an image in a Bootstrap Modal using data fetched from an ajax json response

My current issue involves displaying and editing a record from a database using Bootstrap modal. Everything works fine except for the image rendering - it doesn't seem to display the edited image. While an HTML dataType renders the image correctly, I ...

Tips on un-nesting a JSON array received from an R API

Currently, I have developed an R API using OpenCPU to query a neo4j database and retrieve the results. The output is in the following format: [ { "abc": "aabbcc1", "pqr": "ppqqrr1", "xyz": "xxyyzz1" }, { "abc": ...

Guide to writing a Jasmine test case to verify Toggle class behavior within a click event

My directive is responsible for toggling classes on an element, and it's working as expected. However, I seem to be encountering an issue with the jasmine test case for it. // Code for toggling class fileSearch.directive('toggleClass', func ...

A guide to connecting keyboard events to div elements within a React application

Currently working on a basic react project to gain some practical experience with the library. I aim to develop a simple user interface with blank spaces to be filled in by typing via keyboard input. Here's a glimpse of my progress so far: function ...

PHP array and select that work efficiently

Instead of using multiple foreach-statements, I have been struggling with slow page loading when dealing with 26 students in each class, and some subjects having up to 13 'radnummer'. Examples are shown below. This is the desired output format ( ...

Components from Bower are currently not available

Trying to automate the injection of bower components into my HTML using grunt-wiredep. It seems simple enough, but I'm having trouble setting the correct path to the bower directory when running localhost. Currently, I'm receiving this error: ht ...

The latest version of Spring MVC, 4.1.x, is encountering a "Not Acceptable" error while trying

After creating a Rest Service using Spring MVC4.1.X, I encountered an issue when attempting to return Json output to the browser. The error message displayed was: The resource identified by this request is only capable of generating responses with charact ...

Could anyone assist me in resolving the error stating, "The 'Argument `where` of type UserWhereUniqueInput needs at least one of `id` arguments"?

Upon investigating, I inserted this console log to determine what data is being received: { username: 'aa', gender: 'Feminino', cargo: '2', email: 'a', password: 'a' } Lately, I've been facing this err ...