Iterating over an object and inserting values into a JavaScript object using the ascending count as the identifier

Illustration:

{
     Are you a coffee drinker?: yes,
     Do you like to exercise regularly?: no,
     How often do you eat out at restaurants?: 3 times a week,
     What is your favorite type of cuisine?: Italian
    }
    

Results:

{yes: 1, no: 1, 3 times a week: 1}

Expected results:

{1: "yes", 2: "no", 3: "3 times a week" , 4: "Italian"}
    

Function implemented:

  getPreferences() {
        this.preferenceCount = {};
        for (let key in this.formAnswers) {
          console.log(this.formAnswers)
          if (! this.preferenceCount[this.formAnswers]) {
            this.preferenceCount[this.formAnswers[key]] = (this.preferenceCount[key]+1) || 1
          }
        }
        console.log(this.preferenceCount);
      }
    

Answer №1

To retrieve the values for each key in an object, you can utilize the Object.values method. Subsequently, you can use Array.map to convert these values into an array of objects by using the array index incremented by one as the key. Finally, you can employ Object.assign to flatten this array of objects into a single object:

const obj = {
 "Do you have a monthly student payment?": 133,
 "Do you have a monthly car loan payment?": 150,
 "Do you have a monthly car insurance payment?": 120,
 "How much do you estimate you spend on gas for your car monthly?": 150
};

const out = Object.assign({}, ...Object.values(obj).map((v, i) => ({ [i+1] : v })));

console.log(out);

Answer №2

Using ES5 Syntax

const financialData = {
  "Do you have a monthly student payment?": 133, 
  "Do you have a monthly car loan payment?": 150,
  "Do you have a monthly car insurance payment?": 120,
  "How much do you estimate you spend on gas for your car monthly?": 150
};

var transformedData = Object.keys(financialData).reduce(function(accumulator, currentValue, index) {
    accumulator[index] = financialData[currentValue]
    return accumulator;
}, {})

console.log(transformedData)

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

Is it possible to compare escaped data with the unescaped value of a select box in JavaScript?

On my webpage, I have a functionality that involves fetching select box options through an AJAX request. I then create the select box based on this data, and later use the selected option to retrieve additional information from the response received via AJ ...

Tips for accessing the HTML content enclosed within a specific HTML tag using Python with Selenium

I am trying to extract the source code of an HTML document that is embedded within an <iframe> tag generated by JavaScript. The HTML contents within this <iframe> tag appears as #document, which expands to reveal a full HTML document starting w ...

How can I display a PHP variable in JavaScript?

I am having trouble displaying a PHP variable in Javascript; Below is the code I am using: <script type="text/javascript> $(document).ready(function (){ var n=<?php echo json_encode($count)?>; for(var i=0;i<n;i++){ var div ...

Guide on inserting the elements <label>, <input>, and <span> into a <li> in a particular sequence

var btn = document.querySelector('.add'); var remove = document.querySelector('.draggable'); function dragStart(e) { this.style.opacity = '0.4'; dragSrcEl = this; ...

The webpage hosted on Heroku displays a blank background, requiring users to refresh the page with an F5 key

I developed a group chat program using Python microframework flask, vanilla JavaScript, and Flask-SocketIO. The program is deployed on heroku and can be accessed here: . After deployment, I encountered the following issue: While the program worked fine o ...

Issue with Ajax not triggering PHP script

My first experience with using Ajax to call a php script is not going well. The script doesn't seem to be working at all. Here is the snippet of code where I implemented Ajax: <?php if (isset($_GET['error'])) { switch ($_GET[ ...

"JavaScript function to add objects to an array when button is clicked

var householdData = []; function createMember(age, relationship, smoker) { this.age = age; this.relationship = relationship; this.smoker = smoker; } addBtn.addEventListener("click", addHouseholdMember); function addHouseholdMember() { var ...

Ensuring Consistency in Array Lengths of Two Props in a Functional Component using TypeScript

Is there a way to ensure that two separate arrays passed as props to a functional component in React have the same length using TypeScript, triggering an error if they do not match? For instance, when utilizing this component within other components, it sh ...

Quiz application features various button states for optimal user interaction

I am in the process of creating a quiz that resembles the popular BuzzFeed quizzes such as THIS ONE. Although I have mapped out the logic and have an idea of how to code it to function similarly to the one provided in the link, I am encountering issues wit ...

Several controllers are currently inactive

I have encountered an issue with my code where there are two separate applications with two different controllers, but the second one is not running. Despite being in two different modules, I can't figure out why this is happening. <!DOCTYPE htm ...

What is the best way to extract data from two dropdown menus and send it to separate URLs?

I need assistance with extracting the selected year value from the first dropdown. I would like to append this value to the URL of the header page and also to the options in the second dropdown. This way, when I select a PHP page from the second dropdown ...

Trouble with AJAX request on iPad, works perfectly on desktop

Here is some of my custom plugin code (function ($) { $.fn.createGallery = function(options) { var theObject = $(this); var settings = $.extend({ // Default settings. server: 'http://localhost/jQuery%20Gall ...

Removing an element in Vue.js

Can someone help me with a Vue.js issue I'm having? I'm working on a quiz and I want to add a button that deletes a question when clicked. Here's what I've tried so far: deleteQuestion(index) { this.questions.splice(index, ...

The package.json file engines field specifying the version with a tilde and then a greater than sign (~>)

When a package.json file includes an engines field such as this: "engines" : { "node" : "~>12" }, What is the significance of ~> in this context? ...

problem with saving session data

I am attempting to access data from another page using session storage. On my initial page, named home.html function go_to_faq(qnum){ window.open('FAQ.html', '_blank'); sessionStorage.setItem('key2', qnum); } <a s ...

Retrieve information from an ajax call within an Angular application

I need assistance with 2 requests I have. $.ajax({ type: "POST", url: "http://sandbox.gasvisor.com:9988/uaa/oauth/token", data: "grant_type=client_credentials", headers: { 'Content-Type': 'application/x-www-form-urlencoded&a ...

What is the best way to retrieve the value of a textbox in AngularJS?

Trying my hand at creating a basic web page using angular. I've got 2 textboxes and 2 buttons - one to set a predefined value in a textbox, and the other to add some text. Here's the code snippet: <!DOCTYPE html> <html lang="en" ng-app ...

Puppeteer causes Express to stop listening to incoming requests

As I work on developing a straightforward API that utilizes Puppeteer to execute actions, I encounter an issue where my Express app stops listening once Puppeteer is launched. Below is the script in question: const Apify = require('apify'); cons ...

Is there a way to easily identify the error in my Express application that is preventing my hbs template from running properly?

I am facing an issue with my express code where it is not rendering the data properly. Can someone please assist me in resolving this error? Your help will be greatly appreciated! let express=require('express'); let app=express(); ...

Tips on transforming a JSON array object into a JSON array

**Background:** I have been utilizing lodash to eliminate the empty key from my JSON data. However, upon removal of the keys, it transforms my array into an object. For instance: { "projection": "Miller", "series": [ { "mapPolygons": { ...