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

The React component is failing to display updated data from the Redux store

I've been working with React and Redux, trying to update my counter value in the React view. I can successfully log the latest state of my Redux store, but the changes are not reflecting in my React view. const counter = (state = 0, action) => { ...

Issue with modal-embedded React text input not functioning properly

I have designed a custom modal that displays a child element function MyModal({ children, setShow, }: { children: JSX.Element; setShow: (data: boolean) => void; }) { return ( <div className="absolute top-0 w-full h-screen fle ...

Angular2 scripts are failing to load in the web browser

Setting up my index page has been more challenging than I anticipated. Take a look at my browser: https://i.stack.imgur.com/L4b6o.png Here is the index page I'm struggling with: https://i.stack.imgur.com/Op6lG.png I am completely stumped this tim ...

There appears to be an issue with displaying the graph

I am having trouble understanding how to transfer the values entered in the input to the graph that is displayed successfully. Although the update seems correct, nothing changes when I try to update it and the data remains stagnant. Page.vue <script&g ...

Passing arrow functions for input validation rules to the Stancil component in Vue

I am attempting to implement an arrow function as input rules, similar to the setup in Vuetify at https://vuetifyjs.com/en/api/v-input/#rules. My approach involves passing rules within an array using the following code: <body> <div id="ap ...

Utilize vue.js to cache and stream videos

I'm new to the world of vue.js and I'm facing a certain dilemma. I implemented a caching system using resource-loader that preloads my images and videos and stores the data in an array. Everything is functioning correctly, but now I'm unsur ...

The condition for the result of a jQuery $.post call

I've customized this code obtained from the jQuery website by incorporating a condition into it. However, regardless of the outcome, it consistently enters the first 'if' statement. How can I ensure that my condition is functioning correctly ...

A guide on verifying the username, password, and chosen role from a database through the use of javascript/ajax or alternative validation methods

If the user's name, password, or role is incorrect, I want to display an error message using validations like AJAX/JavaScript. index.php <html> <head> </head> <body> <style> body { wi ...

Can commands be loaded directly into spec.js files in Cypress instead of support/index.js?

Whenever a new file containing Cypress custom commands is written, it is typically added using Cypress.Commands.add() and then imported into support/index.js. The issue arises when dealing with 100 such Custom command files, as loading all of them every t ...

Sequelize associations are not functioning optimally as expected

Trying to display a nested relationship: Cat.hasMany(legs) Leg.belongsTo(cat) Leg.hasOne(paw) paw.hasMany(leg) This is the Cat Model: module.exports = (sequelize, DataTypes) => { const Cat = sequelize.define('Cat', { us ...

Guide to implementing a delay in JavaScript/jQuery code right after invoking an asynchronous function

Is there a way to execute an asynchronous function and then introduce a delay in the subsequent code execution to ensure that the asynchronous operation has completed? I want to avoid wrapping the following code in a function and delaying it, I simply ne ...

Exploring the depths of object properties with Angular, JavaScript, and TypeScript: A recursive journey

Let's consider an object that looks like this: const person = { id: 1, name: 'Emily', age: 28, family: { mother: { id: 101, name: 'Diana', age: 55 }, fathe ...

The onMessage listener in Chrome consistently returns an 'undefined' response

My latest project involves creating a simple chrome extension that utilizes message passing. The goal of the extension is to listen for messages from a specific website (in this case, localhost:8080/*) and respond with a simple "Bye". To test this function ...

I am attempting to create a password validation system without the need for a database, using only a single

Help Needed: Trying to Create a Password Validation Website <script language="Javascript"> function checkPassword(x){ if (x == "HI"){ alert("Just Press Ok to Continue..."); } else { alert("Nope... not gonna happen"); } } ...

Animation that slides in from the left using CSS styling

My current project involves creating a slideshow, and while it is mostly working fine, I am facing an issue with the animations. The animation for sliding out works perfectly, but the animation for sliding in from the left doesn't seem to be functioni ...

Generating and displaying a JSON response

I am having trouble displaying a response on the screen using an AJAX request script with a post method and body value. Here is my code: $('#my-form').submit(function () { $.ajax({ url: 'https://apiurl.com/users', ...

Pace.js doesn't bother waiting for iframes to completely load before moving on

On my website, I am using pace.js but encountering issues with pages containing iframes. Is there a method to ensure that pace.js considers the content loading within those iframes? I attempted to configure paceOptions to wait for the iframe selector to l ...

Setting attributes on an AngularJS Directive element in real time

My goal is to create a directive in AngularJS with a template that can contain other AngularJS directives. All of my directives require an "id" attribute, so I must set the "id" on the directive within the template. However, no matter how I attempt this, A ...

Retrieving JSON data via an AJAX call

Similar Question: Sending PHP json_encode array to jQuery I've created a function that searches a database for a specific name using $.post. It returns user details with matching search criteria in JSON format generated by PHP, like this: Arra ...

Having trouble accessing Kotlin JS from JavaScript

I'm currently experiencing an issue where I am unable to call any Kotlin JS function and receiving an error stating that 'something' is not defined. Initially, I attempted compiling the project with Gradle but found success after following ...