What is the best way to iterate over the JSON response object and strip out the property labels?

// GET - Retrieve login settings
router.route('/login/settings').get((req, res) => {
  let settings =[];
  pool.connect((err, client, done) => {
    client.query('SELECT * FROM public.settings', (err, result) => {
      settings = result.rows;
      let transformedSettings = settings.map(setting => {
        return {
          [setting.key]: setting.value
        };
      });
      res.json({
          settings: transformedSettings,
      });
    });
  });
});

The API routing code above fetches login settings and returns a JSON object with the following structure:

{
  "settings": [
    {
      "key": "TwoFactorAuth",
      "value": "false"
    },
    {
      "key": "sessionTimeout",
      "value": "200"
    }
  ]
}

To modify the JSON response to meet the desired format shown below, you can incorporate a loop in the routing code as demonstrated:

{
  "settings": [
    {
      "TwoFactorAuth": "false"
    },
    {
      "sessionTimeout": "200"
    }
  ]
}

Answer №1

Transform the structure of result.rows items by utilizing array mapping.

Modify line 6 to:

settings = result.rows.map(setting => ({[setting.key]: setting.value}));

This adjustment should be sufficient.

Answer №2

Iterate over each item in the settings array and construct a new object with a single property. The property's name is derived from the key value of the original element, while the value comes from the value element. Finally, replace the current array element with this newly created object.

var settings = response.settings;
for (var i = 0; i < settings.length; i++) {
    var obj = {};
    obj[settings[i].key] = settings[i].value;
    settings[i] = obj;
}

Answer №3

Give this functional snippet a try:

const obj = {
  "options": [
    {
      "name": "DarkMode",
      "status": "enabled"
    },
    {
      "name": "NotificationSound",
      "status": "disabled"
    }
  ]
};

const result = obj.options.map((item) => {
  const newObject = {};
  newObject[item.name] = item.status;
  return newObject;
});

console.log(result);

Answer №4

To incorporate a variable as a key in an object, you can utilize the [key] notation. Give this code snippet a try to update the object:

updatedSettings  = settings.map((item) => {
    var obj = {};
    obj[item.key] = item.value;
    return obj;
});

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

Synchronize your store by utilizing cookies in the nuxtServerInit function of NuxtJS

I am currently working with NuxtJS's auth module and attempting to retrieve the Bearer token along with a custom cookie that holds a sessionType during nuxtServerInit in order to update the store through a mutation. However, I am facing an issue where ...

Looking for a way to store data in local storage so it remains even after the page is reloaded? I tried adding a local storage function, but it doesn't appear to be

I am currently working on a project involving a work day scheduler and I am facing challenges in saving data within the schedule events, like at 8am, and making sure it persists on reload. The colored time block element that changes as hours pass in the da ...

Issue with Django: Unable to fetch data from server response in Ajax

Just starting out with Django and trying to figure out how I can dynamically add content from a python script without reloading the page. In my views.py file, I have two functions - one for uploading a file (home) and another for calling a python script t ...

Leveraging Global Functions with Angular 5

I am faced with the challenge of integrating video.js into my IonicFramework application built using Angular. I attempted to install it via npm, but encountered issues with TypeScript recognizing any importable module, and was unable to find clear document ...

Mastering various techniques for creating styles with makeStyles in React JS Material-UI

As a newcomer to React JS and Material UI, I am experimenting with creating various styles of buttons. Each button should have a unique appearance based on attributes like name= submit, ok, cancel, confirm, alert. App.JS import CssButton from './con ...

Guide on uploading a file to Amazon Glacier with Node.js

While browsing through the Amazon AWS documentation, I stumbled upon this helpful example. var glacier = new AWS.Glacier(), vaultName = 'YOUR_VAULT_NAME', buffer = new Buffer(2.5 * 1024 * 1024); // 2.5MB buffer var params = {vaultName: ...

The issue with Extjs store.proxy.extraParams being undefined appears to only occur in Internet Explorer

I currently have an ExtJs store set up with specific configurations. var fieldsStore = new Ext.create('Ext.data.Store', { model : 'FieldsModel', proxy : { type : 'ajax', url : 'queryBuilder_getQueryDetails', ...

Locate the midpoint index of the initial sequence occurrence within an array

I am trying to determine the midpoint of the first sequence that appears when given multiple strings in a large array For example: var array = ["c6dafc", "c6dafc", "1d2129", "1d2129", "1d2129", "cfcfff", "cfcfff", "ffffff", "1d2129", "1d2129", "1d2129", ...

Enhancing Rails: Tailoring the flash message to suit individual needs

I am embarking on my journey with ruby on rails and could use some guidance with the following scenario. In the application.html.erb file, flash messages are configured to fade out after a few seconds by default. <div id="message" class="modal alert a ...

The blast.js example runs flawlessly on CodePen but encounters issues when run locally

I recently discovered blast.js and am encountering a problem when trying to run an example. The example functions perfectly on codepen, but fails to work on my local machine. The console is showing the following warning and error message. Any assistance fr ...

Converting Excel files to JSON format by importing them and parsing the data

I recently added a "drag and drop file" feature to my website using material-ui-dropzone. I then integrated SheetJS js-xlsx for parsing xlsx data, but I'm struggling to make them work together seamlessly. While I believe the drag and drop part is func ...

Ensure the sum is recalculated whenever the input changes by using the jQuery change event

I am creating a system that requires the total values of multiple inputs to not exceed 100. I have successfully implemented this functionality, but now I need a way to automatically adjust the total if changing one input causes it to drop below 100. Here& ...

retrieve JSON information using JSONP

Currently, I am working with a URL that returns data in JSON format. Here is the URL: http://10.0.1.11/render?target=threshold(400,test)&from=-1mins&format=json&jsonp=? When I enter this URL into a browser, it displays the following JSON re ...

Angular: Selecting all checkboxes outside of an ng-repeat loop

Project Overview In my project, there is a system for managing small product orders. Users have the ability to add order lines and attach one or more products to each order line. While it may be uncommon to have multiple products on the same order line, t ...

Encountering the WRONG_DOCUMENT_ERR: DOM Exception 4 error when attempting to close Fancybox after making edits in inline Tiny

I am encountering a problem with my fancybox that includes a form for collecting user input, which features a tinyMCE editor. When trying to close the fancybox after making substantial edits in the TinyMCE, whether by clicking the close X or submitting the ...

In JavaScript, when using the fetch function with JSON, it is possible to skip the

Here's an example of fetching review data from within a 'for loop': fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline') In this case, some products may not have reviews and will return a 404 response. Th ...

Is it possible to create a return type structure in TypeScript that is determined by the function's argument?

I'm currently stuck on developing a function that takes a string as an argument and outputs an object with this string as a key. For example (using pseudo code): test('bar') => {bar: ...} I am facing difficulties in ensuring the correct ...

Using Vue.js to send user input data to a different page and trigger a method for submission

I am seeking assistance with my first question and hope to receive your support. In my setup, I have a catalogue page that includes a keyword search function and a main page with a search bar. My objective is to automatically redirect any submission from ...

What could be causing the jQuery Mobile DOM element to return 'undefined' when using .val()?

Currently, I am experimenting with Jquery Mobile and facing an issue where my Form elements are returning 'undefined'. I suspect that the problem lies in the fact that my form may not be created when the onclick() function is triggered by the Mem ...

PHP is adding unique characters like   into the database records

Description : Having an issue with adding a text to a content editable div. When clicking the button, I am trying to extract all the text from the div and send it to php successfully. However, when saving it to my database table, the text gets corrupted. A ...