Converting numerical elements in an array to strings

Looking for assistance with reformatting the values in this Array :

[{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}]

I want to convert all the values into strings like so :

[{abcd:"1", cdef:"7"},{abcd:"2", cdef:"8"}, {abcd:"3", cdef:"9"}]

Can anyone help with this task?

Answer №1

Iterate through the array and create a new object for each key value pair after converting them to strings.

const array = [{key1:'value1', key2:'value2'},{key1:'value3', key2:'value4'}, {key1:'value5', key2:'value6'}];

array.map(item => {
  const newObj = {}
  Object.keys(item).forEach(prop => {
    newObj[prop] = item[prop].toString();
  })
  return newObj;
})

Answer №2

const myObjects = [{xyz:10, uvw:3},{xyz:20, uvw:6}, {xyz:30, uvw:9}];

myObjects.forEach(obj => {
    for(let key in obj) {
        if(obj.hasOwnProperty(key)) {
            obj[key] = '' + obj[key];
        }
    }
});

Answer №3

Transforming values in an object can be done using the .map() method along with Object.entries() and spread syntax inside an object literal. The value can be converted to a string using the String function.

var data = [{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}];

var result = data.map(o =>
  ({...Object.entries(o).map(([k,v]) => ({[k]:String(v)}))})
);

console.log(result);


If you prefer mutating the original objects:

var data = [{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}];

for (const o of data) {
  for (const [k,v] of Object.entries(o)) o[k] = String(v);
}

console.log(data);


Another approach is using Object.assign:

var data = [{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}];

for (const o of data) {
  Object.assign(o, ...Object.entries(o).map(([k,v])=>({[k]:String(v)})));
}

console.log(data);

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

Bundling JSPM with an external system JS file

Currently, I am loading my Angular2 file as a System js module from a CDN. Within my project, I have multiple files importing various System js modules of Angular2. However, I am now looking to bundle my local JavaScript files using JSPM. But when I ente ...

JavaScript - Retrieve all properties and methods of an object

Can an object created through a constructor function have its keys listed using the Object.keys() method? Let's consider an example with the following code: function Foo () {} Foo.prototype.bar = 'bar'; Foo.prototype.baz = 'baz'; ...

JavaScript: The Battle of Anonymity - Anonymous Functions vs Helper

I'm currently grappling with a piece of functional style code that is featured in the book Eloquent Javascript: Here's the issue I'm facing: When I have the count() function passing an anonymous function to reduce(), everything seems to wor ...

Guide on utilizing exported API endpoint in Node and Express

Seeking a deeper understanding of express and its utilization of various endpoints. Recently came across an example of an endpoint that reads in a json file, demonstrated as follows: const fs = require('fs'); const path = require('path&apos ...

Nested promises utilized within functional programming techniques

Working on an Angular project involves developing a booking system with various scenarios. The challenge lies in handling different server calls based on the response of a promise, leading to a nested callback structure that contradicts the purpose of prom ...

Populating dropdown menu with data from redux state upon component mounting

I am new to working with react-redux and have successfully implemented dependent dropdown functionality in a react component (Country => State => City). My goal now is to dynamically update the dropdown values based on data received from the redux s ...

Conditional ngOptions in AngularJS allows you to dynamically update the options

Currently, I am working with a select box that iterates through an array of departments to identify eligible parent departments. <select class="editSelectBox" ng-model="dept.parentDepartment" ng-options="dept as dept.name for dept in depts track by de ...

Node.js and EJS are throwing an error, indicating that the file.ejs is unable to identify the variable definitions

I am facing an issue with my express.js server template. A 'x is not defined' error keeps popping up, but I can't seem to find where the problem lies. I even checked a friend's code from the same tutorial, and it works on his machine. ...

What could be causing my asynchronous JavaScript/Node.js function to bypass a significant portion of the code?

Upon calling the function below: async function sql_func(){ console.log('anothertest') async () => { console.log('third test') try { await sql.connect('heres the connection data') ...

jQuery struggles to properly interpret JSON data retrieved from a PHP file

I have successfully encoded WordPress data as JSON for a store locator page, however, I am encountering an issue where the page fails to parse the returned JSON. Even though the file is present and it indeed returns the correct JSON data, I receive a 404 N ...

Managing dynamically loaded scripts in Meteor.js

This poses an interesting query: is there a way to regulate which scripts a client is provided with? I've partitioned my code into dynamically loadable segments using the import('dynamically_loadable_file') method, but each time it's ca ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...

Tips for updating state and rendering in a function component in React Native:

I am attempting to update the state before rendering the component in a function component. While I have found suggestions to use the useEffect hook for this purpose, I am finding the information on the React official site somewhat perplexing. The docume ...

What is the reason why setting 'onClick' as an event handler is not flagged as a syntax error?

I am currently working on a JavaScript code snippet where I am trying to change the headline text when it is clicked. The code I have written is: var headline = document.getElementById("mainHeading"); headline.onClick = function() { headline.innerHTML ...

What are some ways to prevent sorting and dragging of an element within ul lists?

A list styled with bullets contains various items. It is important that the last item in the list remains in a fixed position. I attempted to disable sorting using the cancel option of the .sortable() method, but it only prevented dragging without disablin ...

What is React.js's approach to managing CSS files?

Currently, I am enrolled in Bootcamp at Scrimba where they utilize an online platform for teaching various courses. One of the topics covered is React and involves working with CSS files. When working on my local machine, I typically use the index.css file ...

The duration for which an API Access Token remains valid is extremely brief

I recently started working with APIs and my current project involves using the Petfinder API v2 to develop a website that allows users to search for adoptable animals. The API utilizes OAuth, requiring a key and secret to obtain a token via CURL. However, ...

Why is my Javascript XMLHttpRequest onreadystatechanged event not triggering?

I am facing an issue with my html file and a .txt file stored in the same directory on a webserver. In the html file, I have the following code: <html> <head> <script> window.onload = function() { receiveMessage(); } function recei ...

Modifying the structure of serialized data

After serializing a JS form, the data looks like this: .....&xx=xxx&otherError=&input=SMS&message=sdfgs&...... Can anyone provide guidance on how to replace the value of message with the content of a textarea before making an ajax cal ...

JS implementing a listener to modify a Google Map from a separate class

Currently, I am in the process of migrating my Google Map functionality from ionic-native to JavaScript. I am facing an issue while attempting to modify the click listener of my map from a separate class. The problem seems to be related to property errors. ...