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

Is it possible to call a ref from a different component in React?

I'm currently working on a React chat application and I want the input field where messages are entered to be focused every time you click on the chat box. However, the challenge I'm facing is that the chat box in the main component is separate ...

What is the best way to showcase my customized license plate on the following page?

I need help with incorporating my number plate builder into a website. I have utilized JQUERY and JAVASCRIPT for the styling aspect, but now I want to display the designed plate on the next page. Can someone guide me on how to achieve this using PHP, JQUER ...

Managing reverted MySQL transactions in a Node.js environment

I've been struggling with an issue for a few days now and I'm really hoping that you could provide some assistance. The problem lies in a node.js API using sequelize to interact with a MySQL database. When certain API calls are made, the code i ...

Obtain data from objects within an object

I'm struggling to access this information using JavaScript. This object contains nested objects. Here is how I am retrieving the information: $questions = Question::select('questions.id AS question_id' , 'questions.date', &apo ...

What is the process for incorporating a class into a table within TinyMCE using JavaScript?

I am facing an issue with adding a class to a table. I'd like the following code: <table></table> to transform into this code by clicking a button in tinymce. <table class="try-class"></table> I have added a button, bu ...

A method for applying the "active" class to the parent element when a child button is clicked, and toggling the "active" class if the button is clicked again

This code is functioning properly with just one small request I have. HTML: <div class="item" ng-repeat="cell in [0,1,2]" data-ng-class="{active:index=='{{$index}}'}"> <button data-ng-click="activate('{{$index}}')">Act ...

When attempting to toggle the view on button click, it is not possible to select a shadowRoot

I am facing an issue with my parent component named ha-config-user-picker.js and its child component called edit-user-view.js. Parent Component: It contains a mapping of users and includes the child component tag along with its props. When a click event i ...

React-NextJS encountered an error: TypeError, it cannot read the property 'taste' because it is undefined

Recently, I've been encountering an issue with NextJS that keeps throwing the error message: TypeError: Cannot read property 'taste' of undefined. It's quite frustrating as sometimes it displays the expected output but most of the time ...

"Error message: Undefined index error when trying to decode JSON

In my database, there's a JSON file named articles.json which contains data as follows: { "articles": [ { "id": 1, "title": "a" } ] } Now, I have written a script to decode this JSON file: <?php include "inc/header. ...

Information is inaccessible beyond onBeforeMount in the Composition API of Vue 3

In my code snippet block, I have the following code: <script setup lang="ts"> import ApiService from '../service/api' import { reactive, onBeforeMount } from 'vue' let pokemons = reactive([]) onBeforeMount(async ()=> ...

Step-by-step guide on handling a JSON response from an API using C#

After reading multiple articles online, I still can't figure out how to process a json response from an API call. In my Main() method, I have a simple method that I call. public async void apiTestCall() { var httpCall = new HttpClie ...

Decoding JSON array in C# with deserialization

Trying to deserialize an array from JSON into a C# class using Newtonsoft has been challenging. Despite watching tutorials and reading other questions on this topic, I am encountering difficulties because the array I want is not at the top level of the JSO ...

looking to save a service or factory as a variable

I seem to be at a standstill when it comes to finding a solution for my mvc.NET / angularjs project. So far, I believe I've done a good job abstracting the view to use a controller that matches the type name of the specific controller.cs class: < ...

The Material UI library is signaling that there is an unidentified property called `selectable` being used with the <table> tag

Whenever I try to add the selectable attribute to the Table component in Material-UI using React JS, I encounter an error. Despite checking that selectable is indeed included in TableProps, the issue persists. List of Dependencies : "material-ui": "1.0.0 ...

Is there a way to update a JSON key using the "onchange" function in React?

I'm facing an issue. I have a form with two inputs. The first input is for the key and the second input is for the value. I need to update the values in the states whenever there is a change in the input fields, but I'm unsure of how to accomplis ...

The closest comparison to the For In method in JavaScript in the Apex programming

I am looking for a way in Apex to iterate through all the fields of a list of account objects without having to resort to using JavaScript. Currently, I can achieve this with the following code snippet in JavaScript, but I prefer to keep things within the ...

Unable to pass the jQuery value - troubleshooting tips for Laravel

JavaScript Issue return response()->json([ 'category' => $category, 'editRoute' => $artistCategoriesEditRoute ]); AJAX Response category Object { id: 1, title: "tt", parent_id: 0, … } id ...

Reorganize the placement of table columns between different rows

I am currently using a software program that automatically generates a form based on the selected options. The code for this form is generated in tables, which I am unable to directly edit. However, I would like to have the Amount, radio buttons, and their ...

Issue encountered while attempting to log out a user using Keycloak in a React JS application

I'm currently working on implementing authentication for a React JS app using Keycloak. To manage the global states, specifically keycloackValue and authenticated in KeycloackContext, I have opted to use React Context. Specific Cases: Upon initial r ...

"Embedding social content within an iframe may result in the element being unresponsive

I have a setup where I'm utilizing social embed to include Instagram content in the footer. When I insert the provided iframe code, the layout looks correct but the content is not clickable. <iframe src="https://embedsocial.com/facebook_album ...