Transformation of JSON data from Array to Object

I have a JSON data structure that looks like this:

{
  tag: 'new-tag',
  stream_subjects: [1, 2, 3]
}

My goal is to transform it into the following format:

{
  tag: 'new-tag',
  stream_subjects: [
    {subject_id: 1},
    {subject_id: 2},
    {subject_id: 3}
  ]
}

I am looking to achieve this transformation using

Object.keys(data).forEach((k) => { }
. Can someone please guide me on how to accomplish this task?

Object.keys(params.data).forEach((k) => {
  console.log(`${k} - ${params.data[k]}`);
  if (typeof params.data[k] === 'object') {
    temp[k] = {};
    for (const innerKey in params.data[k]) {
      temp[k].subject_id = params.data[k];
    }
  } else {
    temp[k] = params.data[k];
  }
  console.log(temp);
});

Answer №1

I made some adjustments to the code you provided. Take a look at the modified version below.

const result={};
Object.keys(inputParams).forEach((key) => {
  console.log(`${key} - ${inputParams[key]}`);

  if (Array.isArray(inputParams[key])) {
    result[key]=[];
    inputParams[key].forEach(item => result[key].push({'id': item}));

  } else {
    result[key] = inputParams[key];
  }
  console.log(result);
});

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

`AngularJS Integration in Liferay`

Utilizing AngularJS globally within Liferay Portal is a strategy I would employ. The flexibility of AngularJS allows for dynamic views in web applications, enhancing the readability and development speed of the environment. I prefer leveraging the declara ...

Updating dynamic parameter in a NextJS 13 application router: A complete guide

In my route user/[userId]/forms, I have a layout.tsx that includes a Select/Dropdown menu. The dropdown menu has options with values representing different form IDs. When the user selects an item from the dropdown, I want to navigate to user/[userId]/form ...

Ways to guide users through a single-page website using the URL bar

I currently have a one-page website with links like <a href="#block1">link1</a>. When clicked, the browser address bar displays site.com/#block1 I am looking to modify this so that the browser shows site.com/block1, and when the link is clicke ...

What is the best way to delete rows from a table that was created using a JQuery AJAX response?

I am currently working on a coding project where: The user is required to input a location, Clicks on a button to execute a GET call in order to fetch data based on the specified location, and A table is then filled with the retrieved data. My goal is t ...

I am looking to create a div that can consistently refresh on its own without needing to refresh

I have implemented a comment system using ajax that is functioning well. I am looking to incorporate an ajax/js code to automatically refresh my "time ago" div every 5 seconds so that the time updates while users are viewing the same post. Important note: ...

The functionality is verified in Postman, however, it is not functioning properly when accessed from my client's end

I am working on a project where I have a button in my client's application that is supposed to delete a document from a MongoDB collection based on its ID. Here is the backend code for this functionality: index.js: router.post('/deletetask' ...

Find all the different ways that substrings can be combined in an array

If I have a string input such as "auto encoder" and an array of strings const arr = ['autoencoder', 'auto-encoder', 'autoencoder'] I am looking to find a way for the input string to match with all three values in the array. ...

Display the hover effect for the current card when the mouse is over it

When the mouse hovers over a card, I want only that specific card to show a hover effect. Currently, when I hover over any card, all of them show the hover effect. Is there a way to achieve this in Vue Nuxtjs? Here's what I am trying to accomplish: ...

Ways to verify the existence of a particular word within a nested array of objects

I have implemented a text input field and a send button for submitting the entered text. Utilizing the react-mention library, I am able to handle hashtags in the text. As the user types, if they include "#" it displays available hashtags from the data set. ...

The memory usage steadily increases when you refresh data using the anychart gantt chart

I have a basic anychart code to update a gantt chart every second: function initializeSchedule(){ anychart.onDocumentReady(function () { anychart.data.loadJsonFile("../scheduler?type=getschedule", function (data) { documen ...

What steps should I take to generate a stylized date input in javascript?

Looking to dynamically create a date string in JavaScript with the following format: dd-MMM-yyyy Need the dd part to change between 1 and 29 each time I generate the variable within a loop Month (MMM) should be set as Jan ...

Step-by-step guide on integrating a specific location into Google Maps using React.js

I'm in the process of revamping my website using Reactjs. I want to incorporate a specific Google location with reviews on the map, similar to how it appears on this example (My current website is built on Wordpress). As of now, all I've been ab ...

Unexpected absence of Aria tags noticed

I've been working on integrating ngAria into my project. I have injected it into my module and created the following HTML: First Name: <input role="textbox" type="text" ng-model="firstName" aria-label="First Name" required><br> Employee: ...

Unexpected behavior with AJAX success function not being executed in jQuery despite console logs showing otherwise

I'm facing an issue with the following code snippet: $('a.like').on('click', function(e){ e.preventDefault(); var object_id = $(this).data('id'); var token = $(this).data('token'); ...

How to iteratively process JSON array using JavaScript?

I am currently attempting to iterate through the JSON array provided below: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "<a href="/cdn-cgi/l/email-pro ...

Using JavaScript, you can add an article and section to your webpage

Currently, I am utilizing AJAX to showcase posts. My objective is to extract each property from a JSON object that is returned and generate an <article> for the title followed by a subsequent <section> for the content. While I can successfully ...

Store the checkbox's data in the database for safekeeping

Hey there, I'm working on saving the value of a checkbox using PHP. The twist is that the value is generated through JavaScript. How can I handle this scenario and save the value using PHP? Checkbox: <input type='checkbox' name='ca ...

Tips for creating a cursor follower that mirrors the position and size of another div when hovering over it

I am trying to create a cursor element that follows the mouse X and Y position. When this cursor hovers over a text element in the menu, I want it to change in size and position. The size of the cursor should match the width and height of the text being h ...

The useRoutes function is returning null despite the correct pathname being provided

Check out my React code snippet! I've got the Component nestled within a micro-frontend application, which is then brought into the main app using module federation. // embedded in my microfrontend. const path = '/another-component-path'; f ...

Listener for body keystrokes

Is there a way to trigger a function when the space bar is pressed on the page, without it being called if an input field is focused? Any thoughts or suggestions? The current code triggers the function even when an input bar is focused: $(document).keydo ...