Converting values into keys and vice versa in JavaScript: A comprehensive guide

I have an array of Objects where I want to convert the first value into a key and the second value into a value. Please review the question below along with my desired output:

 [
  {
    "name": "Unknown",
    "value": "RAHUL"
  },
  {
    "name": "FirstName",
    "value": "WILLEKE LISELOTTE"
  },
  {
    "name": "LastName",
    "value": "DE BRUIJN"
  }
]

The expected Object format should be like this:

{
"Unknown": "RAHUL"
},
{
"FirstName": "WILLEKE LISELOTTE"
},
{
"LastName": "DE BRUIJN"
}

Answer №1

ONLY IF your intention is to generate a fresh array, you can achieve this by using the map function on the original array. There's no need to explicitly create a new array and push elements into it, as that would be unnecessary duplication of code:

const testData = [{
    "name": "Unknown",
    "value": "RAHUL"
  },
  {
    "name": "FirstName",
    "value": "WILLEKE LISELOTTE"
  },
  {
    "name": "LastName",
    "value": "DE BRUIJN"
  }
];

const newData = testData.map(nameObject => {
  return {
    [nameObject.name]: nameObject.value
  }
});
console.log(newData);

Answer №2

To achieve this, simply use square brackets for accessing the value of a specific property named "name".

let newArray = []

testData.map((data) => {
    newArray.push({ [data.name]: data.value })
})

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

Nextjs couldn't locate the requested page

After creating a new Next.js application, I haven't made any changes to the code yet. However, when I try to run "npm run dev," it shows me the message "ready started server on [::]:3000, url: http://localhost:3000." But when I attempt to access it, I ...

Utilizing Ajax and jQuery to verify the initial password input in real-time as the user types

My goal is to create a Change Password page where users can enter their original password and have it instantly checked for correctness without the need for page refresh. I want to display a checkbox image next to the text box when the password is correct. ...

Using Vue.js, learn how to target a specific clicked component and update its state accordingly

One of the challenges I'm facing is with a dropdown component that is used multiple times on a single page. Each dropdown contains various options, allowing users to select more than one option at a time. The issue arises when the page refreshes afte ...

Conceal and reveal text with a simple user click

Currently, I am working on a website project that utilizes bootstrap. However, I am facing some uncertainty regarding how to effectively hide and display text: <nav class="navbar navbar-light" style="background-color: #e3f2fd;"> ...

Discover the secret to opening two JPG files on YouTube using just one URL!

I was curious about the way YouTube thumbnails function. Here is an example thumbnail from a random YouTube video. There is an hqdefault.jpg in the URL, followed by some variables that indicate the size. If we remove or change these variables, a larger im ...

An effective method for transferring form input and music between pages utilizing JavaScript

I've been grappling with this issue for quite some time now. On the initial page, I have a form like this: <form id="user" name="user" method="GET" action="the-tell-tale-heart.html"> Name: <input type="text" name="name"> & ...

Is your href in javascript not functioning properly?

Recently, I completed the development of a mobile web application. Overall, everything seems to be working smoothly except for one issue: there is a link with JavaScript in its href that is causing problems. Strangely enough, this link works perfectly fi ...

Struggling with setting up a search bar for infinite scrolling content

After dedicating a significant amount of time to solving the puzzle of integrating infinite scroll with a search bar in Angular, I encountered an issue. I am currently using Angular 9 and ngx-infinite-scroll for achieving infinity scrolling functionality. ...

Incorporate a vertical scrollbar in the tbody while keeping the thead fixed for smooth vertical scrolling

I'm seeking a solution to implement horizontal and vertical scroll for my table. Currently, the horizontal scroll is working fine, but when trying to add vertical scroll, the table header also moves along with it. Is there a way to keep the table hea ...

Instructions for inserting <tr></tr> after every fourth iteration of <td></td> in the loop

I am trying to create a list of twenty people with each tr containing 4 people, and I want to break from the loop after every fourth number. Each td value should be incremented in order. This is the code snippet I have been working on: <?php for ($i ...

Angular 2 - AOT Compilation Issue: Running Out of JavaScript Heap Memory

I've been working on an angular2 project and when I try to build the AOT package using the command below, I encounter errors: ng build --aot --prod The errors returned are related to memory allocation failures and out of memory issues in the JavaS ...

Avoiding memory leaks in Reactjs when canceling a subscription in an async promise

My React component features an async request that dispatches an action to the Redux store from within the useEffect hook: const fetchData = async () => { setIsLoading(true); try { await dispatch(dataActions.fetchData(use ...

Monitoring of access controls on Safari during uploads to S3

Safari 10.1.2 Encountering an issue intermittently while attempting to upload PDF files to S3 using a signed request with the Node aws-sdk. Despite working smoothly 90% of the time, have been pulling my hair out trying to resolve this problem. Could it be ...

The dreaded Heroku Node.js error H10 strikes again: "Application crashed"

I recently embarked on my journey to learn NodeJS and attempted to deploy it on Heroku. However, when I used 'heroku open,' the following error log appeared: 2020-10-08T14:19:52.778660+00:00 app[web.1]: at Module.load (internal/modules/cjs/loa ...

Embedding Array into Mongodb is an efficient way to store and

Whenever I attempt to store array data within MongoDB using the query below, it always shows a success message without actually storing any data in an empty array inside MongoDB. My goal is to successfully store array data inside MongoDB as shown in the f ...

Images flicker as they transition

Within my HTML body, I have the following: <a id="Hal9000"> In addition, there is a function included: function Hal(MSG){ document.getElementById("Hal9000").innerHTML = "<img src=\"+preloadImage("HAL9000.php?Text="+MSG)+"\"\>" ...

Is there a way to keep the text animation going even when I'm not hovering over it with the cursor?

Is there a way to make text continue animating on the page even when the cursor is not placed on it? I understand the hover function, but how can I ensure the text keeps animating without interruption? $(document).ready(function () { $("#start&q ...

Transform the elements of a tensor in TensorFlow into a standard JavaScript array

Having utilized the outerProduct feature within the TensorFlow.js framework on two 1D arrays (a,b), I am faced with a challenge in obtaining the values of the produced tensor in regular JavaScript format. Despite attempts using .dataSync and Array.from(), ...

Sending form data to the server using JavaScript: A step-by-step guide

Currently, I am dealing with the configuration of two servers. One server is running on React at address http://localhost:3000/contact, while the other is powered by Express at address http://localhost:5000/. My goal is to transmit form data as an object v ...

Generating Unique Random DIV IDs with JavaScript

Does anyone know of a JavaScript solution to generate unique random DIV IDs? I am currently using PHP for this purpose. <?php function getRandomWord($len = 10) { $word = array_merge(range('a', 'z'), range('A', &apos ...