Changing an array of objects to numerical values

I'm new to the world of JavaScript/TypeScript and I currently have an array filled with objects.

My goal is to convert the value into an integer. Right now, I am achieving this by using the following mapping method:

var k = [{key: "apples", value:"5"}, {key: "orange", value:"2"}];
var output = Object.entries(k).map(([key,value]) => ({key,value}));

console.log(output)

The desired output would be:

[{key: "apples", value:5}, {key: "orange", value:2}]

Answer №1

Avoid using Object.entries() on your array, as you can directly utilize .map() on the k array. Deconstruct each object to extract its value property and then map it to a new object with the value converted to a numeric value using the unary plus operator (+value):

const k = [{key: "apples", value:"5"}, {key: "orange", value:"2"}];
const output = k.map(({value, ...rest}) => ({...rest, value: +value}));

console.log(output)

If you prefer to modify the array in-place, iterate over the objects within it using a .forEach loop, and update the value by accessing it with dot notation like this:

const k = [{key: "apples", value:"5"}, {key: "orange", value:"2"}];

k.forEach(obj => {
  obj.value = +obj.value; // Use `+` for string-to-number conversion
});
console.log(k)

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

I aim to add and modify the quantity of a specific item ID

When the item id already exists, the quantity should be added to the incoming quantity. If the id does not exist, then insert the id and its quantity. Here is an example of what should be inserted into the table: if item_id=array(24,25); quantity=arra ...

Designing the database structure for a Q&A website powered by MongoDB

Looking for some assistance as I embark on creating a website similar to Yahoo Answers or StackOverflow (in a different category with no competition). My main hurdle right now is figuring out the best approach to structuring the database for user and quest ...

The Epub text box feature is malfunctioning

I have a quiz task in an epub format where users need to enter their answers in a text box after reading the question. However, I am facing an issue where the text box does not display the keyboard for typing the answer. Is there a solution using javascr ...

Changing element visibility based on AJAX interactions

As a novice, I am struggling to modify this code. This particular example fetches a stock quote (including the day's low and high) from a PHP file using Ajax. The result is then embedded in the page itself, with an animated GIF indicating progress. ...

Encountering issues with innerHTML displaying undefined results while trying to retrieve and showcase data from a database through the use

This is a sample script for fetching data from a database using AJAX. <!DOCTYPE html> <html> <head> <script type="text/javascript"> function loadJSON() { var data_file = "http://www.example.com/data/connect.php"; var xmlhttp; ...

Rows are not being displayed in JQgrid

Check out this JavaScript code: <script type="text/javascript> $(function () { $("#list").jqGrid({ url: "/Movies/GetAllMovies", datatype: "json", mtype: "GET", colNames: ["Id ...

Using Angular's filter service within a controller

Just starting out so please be kind!! Encountering an issue with Angular 1.3 while using a Stateful Filter within a controller. In brief, when utilizing the $filter('custom')(data) method instead of the {{ data | custom }} method - and the cust ...

JavaScript method parameters are essential components that help define the methods

Can someone explain how function definitions work within a method in Javascript? An example I'm struggling with is in AngularJS: sth.controller('ctrlname', function ($scope, $ionicModal, par3, par4){ //code }); Another piece of code ...

Changing a callback function into a promise in Node.js for OpenTok integration

MY FUNCTIONAL CODE (SUCCESSFULLY WORKING!) I have developed a function with callback to generate tokens and create sessions for OpenTok. This function is then exported to the application. The function //Dependencies var opentok = require('./ot&ap ...

Vue.js and Onsen UI app displaying broken images

I tried the code below to display an image in my Vue.js and Onsen UI App, but unfortunately the images are not appearing. <div class="footer_logo"> <ul> <li class=""><img :src="logo" alt="logo" /></li> </ul ...

The assets on the page are not loading inside their designated containers

While conducting functional tests with nightwatch.js, I encountered a discrepancy between my local environment and the containerized environment. In the container environment, which is crucial for integrating into my CI pipeline and running automated tests ...

Identify when a click occurs outside of a text input

Whenever text is typed into the textarea, the window changes color. The goal is to have the color revert back when clicking outside the textarea. <textarea class="chat-input" id="textarea" rows="2" cols="50" ...

Store the arrays in a JSON file before utilizing Array.push() to append data into it

I'm currently developing a calendar software and I want to store events in a JSON file. My strategy involves nesting arrays within arrays in the JSON format, allowing for easy iteration and loading during program initialization. My main question is: ...

Flawless Carousel - Flipping the Sequence

I am currently implementing Slick Carousel on a website that I am working on. One challenge I am encountering is trying to get the "slider-nav" to move in the opposite direction than it normally does. For instance, at the moment, the order goes like this ...

How can I incorporate a new method into the prototype of multiple objects simultaneously?

Imagine I am in possession of 100 different objects var a={name:'a'}; var b={name:'b'}; ... ... var xyz={name:'xyz'}; I am looking to incorporate a method into each object that will execute a specific action for all objects, ...

Prevent secret select fields from being submitted within a form

In my interface, there are a couple of dropdowns where a user can select the first option and based on that selection, a new dropdown will appear. Currently, when posting the form, all the select dropdown values are included in the post data, even the hid ...

What is the best way to present retrieved JSON data from a database in Node.js without using the JSON format?

Here is the code snippet: var http=require("http"); var fs = require("fs"); var express = require("express"); var app = express(); var path = require("path"); var mysql = require('mysql'); var ejs = require("ejs") var bodyParser = require(&apos ...

Unable to integrate npm package into Nuxt.js, encountering issues with [vue-star-rating] plugin

Just starting with nuxt js and running into issues when trying to add npm packages. Below are my attempts. star-raing.js import Vue from 'vue' import StarsRatings from 'vue-star-rating' Vue.use(StarsRatings) nuxt.config.js plugi ...

I am having an issue with uploading multiple files asynchronously to Firebase storage and retrieving their URLs

My issue revolves around uploading multiple files to Firebase storage after adding an image. The upload works fine, but I encounter a problem when trying to retrieve the download URLs for these files. While getting URLs for multiple files is successful, I ...

The challenge of performance in AngularJS Material textareas

When working with a form containing 40-50 textareas, the default option md-no-autogrow can lead to severe performance issues. The function causing this issue can be found at this link. Disabling md-no-autogrow means losing the resize functionalities. Wh ...