"Using Typescript, we can switch the keys and values in a JSON object to their corresponding values and

I have been attempting to switch keys with values and vice versa, but I haven't been able to find the correct solution using JavaScript/TypeScript.

  course =  
  [ 
   { 
     "name" : "John",
     "course" : ["Java", "Python"]
   },
   { 
     "name" : "Michel",
     "course" : ["Java", "Python", "Ruby"]
   }
   ]

The desired JSON output should be:

  result = [
   {
     "course" : "Java",
     "name" : ["John", "Michel"]

   }, 
   {
     "course" : "Python",
     "name" : ["John", "Michel"]
   },
   {
     "course" : "Ruby",
     "name" : ["Michel"]
   }

   ]

Answer №1

Check out this JavaScript solution below. By utilizing the reduce method, I've structured the data into an intermediate object:

{
  HTML: {
    tech: "HTML",
    devs: ["Alice", "Bob"]
  },
  CSS: {
    tech: "CSS",
    devs: ["Alice", "Bob"]
  },
  JavaScript: {
    tech: "JavaScript",
    devs: ["Bob"]
  }
}

Then, I'm using Object.values on this intermediate object to extract the values array as requested.

const developers = [    
  {      
    "name": "Alice",     
    "techs" : ["HTML", "CSS"]   
  },   
  {      
    "name" : "Bob",
    "techs" : ["HTML", "CSS", "JavaScript"]
  }   
]

const output = Object.values(developers.reduce((acc,{name, techs}) => {
  techs.forEach(t => {
    acc[t]??={tech:t,devs:[]}
    acc[t].devs.push(name)
  })
  return acc
},{}))

console.log(output)

Answer №2

const students = [{
    name: 'Emma',
    subjects: ['Math', 'Science'],
  },
  {
    name: 'Lucas',
    subjects: ['English', 'History', 'Geography'],
  },
]

const temp = students.reduce((acc, value) => {
  value.subjects.forEach(subject => {
    if (!acc[subject]) {
      acc[subject] = []
    }

    acc[subject].push(value.name)
  })

  return acc
}, {})

const result = Object.entries(temp).reduce((acc, [subject, name]) => {
  acc.push({
    subject,
    name,
  })

  return acc
}, [])

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

iOS app launch does not trigger Phonegap handleOpenURL

Receiving an alert message when the app is open in the background. However, when I close the app from the background and then relaunch it, the alert message doesn't appear. The handleOpenURL function cannot be invoked in JavaScript when the app is lau ...

Dynamically adjust row height in AG Grid within an Angular application based on the visibility of other columns

My current AG-Grid version is 21.2.1, and I am unable to upgrade it for certain reasons. I have successfully implemented wrapping cell content to ensure all content is visible. Additionally, I have buttons in my application to toggle the visibility of col ...

Is it possible to iterate over a non-reactive array in a Vue template without having to store it in a data property or computed property?

Presented below is a static array data: const colors = ["Red", "Blue", "Green"]; To display these values in my markup, I can use the following method in React: import React from "react"; // Static array of colors const colors = ["Red", "Blue", "Green"] ...

Implementing a feature in ReactJS that enables users to select a minimum and maximum limit for checkboxes

I have developed a unique React application that incorporates JSON values into checkbox elements. The JSON data includes both minimum and maximum required values. I successfully implemented a function to set the checkboxes' maximum value based on the ...

What are the steps to start up a NodeJS API using an Angular app.js file?

Currently, I am following various online tutorials to develop a web application using the MEAN stack and utilizing a RESTful API. I have encountered some challenges in integrating both the API server and Angular routes. In my project, I have a server.js f ...

Converting Json data without key names into C#

Trying to deserialize a JSON string into a C# object, but the JSON format is not valid and cannot be changed as it comes from a device. The [] brackets need to be replaced by {} for it to resemble a valid object: [2, "2", "text", {Object}] A custom class ...

What could be causing the Javascript Dynamic HTML5 Table to not display on the page?

I have a program that calculates the total price of products based on a specified quantity and updates an HTML table with these values. To demonstrate this, I am constantly taking input using an infinite loop. <!DOCTYPE html> <html> ...

Using Angular 2's dependency injection to inject several instances at once

I have developed an "Messages" injectable that serves as a service for fetching a user's messages. This class relies on a "Database" class to log in to the backend using the user's credentials. Now, I aim to create a test scenario where 2 users ...

Troubleshoot JavaScript in a Firefox browser extension

I have been developing a Firefox addon that relies heavily on JavaScript. The addon serves as a UI recorder with a popup window containing specific buttons that interact with a tab in the main window. When I try to debug the addon using the debugger in ei ...

Node.js retrieves a single row from a JSON array with two dimensions

I am working with a two-dimensional JSON array and I am able to retrieve data from the first dimension using data["dimension-1"], but I am struggling to access data from the second dimension using data["dimension-1"]["dimension-2"]. What is the correct m ...

Modifying the background image of the <body> element in CSS to reflect the season based on the current month in the calendar

I'm struggling to change my HTML background based on the date. The code I've tried isn't working as expected and I can't seem to find any relevant examples to guide me. My goal is simple - I want the background of my HTML page to be ch ...

Creating a OneToMany relationship in NestJS entity model

In my current project with NestJS, I am working on defining entity fields. While I have successfully defined a ManyToOne relation, I am facing difficulties in setting up the syntax for a OneToMany relation to match the structure of my other relationships. ...

Error: The expression `xmlDoc.load` returns a value of undefined, which is not an object

My current challenge involves loading an XML file using Javascript in IE, Firefox, and Safari. I have yet to find a function that works well across all three browsers. The load function I am currently using is similar to the one found in w3schools tutorial ...

Data is not being displayed in the Angular table

Currently, I am working on developing a time tracking application as part of a project. However, I have encountered an issue while attempting to showcase all the entries in a table format (as shown in the image below). Despite having two entries according ...

Instead of providing a list of Django models, opt to return a JSON response instead

As a beginner in python and Django, this marks my debut project. I have been following a tutorial that generates a list of objects, but now I aim to obtain the data in json format. My attempts with JsonResponse and json.dump have not yielded the desired r ...

Design a function that accepts a string parameter and outputs an encoded (h4ck3r 5p34k) rendition of the input string

function convertToHacker(str){ for (var i=0; i <str.length;i++) { if (str[i]==="a") {str=str.replace("a","4")} else if (str[i]==="e") {str=str.replace("e","3")} else if (str[i]==="i") {str=str.replace("i","1") ...

Unable to run unit tests on project using my custom React library

If any of you have encountered this issue or know how to solve it, please help me. I created an NPM package that can be found at https://www.npmjs.com/package/@applaudo/react-clapp-ui It installs and runs smoothly in other projects using create react app; ...

What is the best way to access the "Path" file stored in a JSON file using Python?

Extracting Data from a JSON File [{"Attachment": [ { "Page:": [ { "Path": "a\\b\\c.pdf", #field to be extracted "PageID": 1 } ] } ], "ID": 1322 ...

Accessing Element Content Without Identifiers in JavaScript

http://jsfiddle.net/n253R/3/ Make sure to check the link above. I'm looking to change the color of numbers based on their value. This needs to be applied to multiple numbers within different Wordpress posts. Currently, I am only able to affect one n ...

Is there a way to specify this component without it being nested within the parent element?

So I have this component nested within another one const selectColumn = useMemo<ColumnDef<Person>[]>( () => [ { id: "select", header: ({ table }) => ( <IndeterminateCheckbox {.. ...