What is the best way to transform an array of key–value objects into an array of objects containing just one property?

I am working with an array of objects that looks like this:

[
  { "key": "fruit", "value": "apple" },
  { "key": "color", "value": "red" },
  { "key": "location", "value": "garden" }
]

My goal is to transform it into the following format:

[
  { "fruit": "apple" },
  { "color": "red" },
  { "location": "garden" }
]

Could someone provide guidance on how to achieve this using JavaScript?

Answer №1

If you're looking to transform data in JavaScript arrays, consider using the .map method.

var data = [
  {"key":"fruit","value":"apple"},
  {"key":"color","value":"red"},
  {"key":"location","value":"garden"}
];

var result = data.map(function (e) {
  var element = {};
  element[e.key] = e.value;
  
  return element;
});

console.log(result);

You can also achieve this with ES2015 syntax:

var result = data.map((e) => {
   return {[e.key]: e.value};
});

For a working example, check out this Example.

Answer №2

An arrow function is used here to transform data stored in a variable named arr

arr.map(e => {
    var obj = {};
    obj[e.name] = e.price;
    return obj;
});

This action creates a fresh Array without altering the original one

To make it more concise, it can be written in a single line like this

arr.map(e => ({[e.name]: e.price}));

In case arrow function support is not guaranteed, you would need to write out the long version

arr.map(function (e) {
    var obj = {};
    obj[e.name] = e.value;
    return obj;
});

Answer №3

To achieve your desired outcome, you can either utilize the map function as recommended in previous responses, or implement the code snippet below:

const data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}];
const obj = {};

for(let i = 0; i < data.length; i++) {
  obj[data[i]["key"]] = data[i]["value"];
}

Answer №4

When working with JavaScript, both obj.property and obj['property'] will yield the same result.

obj['pro per ty'] // works
obj.pro per ty // does not work

Another example:

var a = 'property';
obj.a == obj.property // => false
obj[a] == obj.property // => true

Give it a try yourself!

var data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}]
var new_data = [];

var data_length = data.length; // optimization for loop
for (var i = 0; i < data_length; i++) {
    var item = data[i];
    new_data[i] = {};
    new_data[i][item.key] = item.value;
}
console.log(new_data);
// [{"fruit":"apple"},{"color":"red"},{"location":"garden"}]

Answer №5

What you currently possess is an array filled with objects, each containing two attributes: key and value. If you are unfamiliar with using map, an alternative method would be to utilize a forEach loop on this array and restructure the information. Consider implementing something similar to the following:

function() {
     var newArray = [];
     oldArray.forEach(function(x){
     var obj= {};
     obj[x.key] = x.value;
     newArray.push(obj);
    });
  console.log(newArray);
}

In this scenario, 'oldArray' represents your original dataset.

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

Tips for implementing an autoscroll feature in the comments section when there is an abundance of comments

Having a large number of comments on a single post can make my page heavy and long sometimes. This is the current layout of my post comment system: Post 1 Comment for post 1 //if comments are more than 3 <button class="view_comments" data-id="1">Vi ...

Error: TypeScript encountered an issue while attempting to access a property that is undefined

I just can't seem to figure out what's missing here. Running the following code gives me this error: Uncaught TypeError: Cannot read property 'addEventListener' of undefined" class Editor{ public co ...

Conceal div elements and retain their status when the page is reloaded or switched

I currently have 3 div elements displayed on a webpage: header-div fixed_menu_div page_cont Each of these divs are styled with the following CSS properties: #header-div { top:0; left:0; display:inline; float:left; } #page_cont { mar ...

Verify if the element is positioned at the top of the screen using the Selenium JavaScript web driver

Currently utilizing the Selenium web driver from this link to test a website. My goal is to determine if my view is positioned at the top of the entire screen. I have tried using both isDisplay() and getLocationInView, but they only provide absolute posit ...

Reposition the span element to the right of the div tag

I need help adjusting the positioning of the elements in this HTML code. How can I move the span element with the image to the right of the div tag? Here is the code snippet: <div style='width:600px;padding-top: 2px;padding-bottom: 1px'& ...

What is the best way to ensure all JavaScript is fully executed on a webpage before utilizing Selenium with Python?

As I work on my webpage, I am using Selenium with Python to locate specific elements within it. However, a challenge that I am facing is that the elements I need are dynamically generated through JavaScript. Upon examining the page source provided to my S ...

Issue with generating random cells in a table using a loop

Within my HTML code, I have a table constructed using the table element. To achieve the goal of randomly selecting specific cells from this table, I implemented a JavaScript function that utilizes a for loop for iteration purposes. Despite setting the loop ...

Is there a way to execute v-for once the created() lifecycle hook has finished running?

In my current project, I am faced with the challenge of including avatars in notifications. Despite my efforts, I have not been able to solve this issue independently. The Vue.js template below demonstrates how I have attempted to add avatars to each notif ...

Combining JS Tree and Datatables for Enhanced Functionality

I am facing a challenge on my webpage where I have two columns. The left column consists of a checkbox jstree, while the right column contains a table using datatables. Both the table rows and tree are loaded at the start. My goal is to display a row when ...

Tips for linking various points within an array

I am struggling with efficiently creating separate chains from points that have overlapping lines. My array consists of simple Point objects in no particular order, and I can use an "intersect" function to test them. The end goal is to have an array of ch ...

How to substitute "</div>" using JavaScript's .replace method

I have a string that looks like this: this is an example of </div> My goal is to use the .replace method to replace </div> with something else. content.replace(/<\/div>/g,'function'); //remove </div> Unfortunately ...

Issue with 'for' loop iteration over object array

Can someone help me understand why I am getting the unexpected result "6 You have not watched undefined undefined" in the browser console when running this simple code? var films = [{ title: "The Mummy", hasWatched: true, stars: "5 stars" ...

What are some effective techniques to optimize this node.js code and eliminate redundancy?

I am currently in the process of setting up a basic template for my demonstration project and writing my first node.js program. The piece of code below is functioning properly for my initial test, but it contains duplicated sections - Getting connection, E ...

Steps to show submenus upon hovering over the main menu items

I am trying to create a vertical menu with multiple levels using HTML and CSS. Here is the code I have written so far: <ul> <li>Level 1 menu <ul> <li>Level 2 item</li> <li>Level 2 item</li&g ...

What to do when a JWT token expires and how to generate a fresh token?

I am currently dealing with a problem regarding JWT (JSON Web Token) authentication in my application. At times, when I make API requests, I encounter the following error response: { "success": false, "message": "jwt expired" } I am aware that this er ...

Trigger a modal popup upon page load event generated from the server side using C#

I am trying to display a modal popup based on certain conditions during the page load event, but I am facing some issues. This is my modalPopup code: <script type="text/javascript"> function openModal(message, header, url) { $('#my ...

Extracting text from an HTML file and passing it to an Express.js server: A beginner

Currently, I'm attempting to retrieve the values from an HTML text field and store them in variables. I require HTML to capture these values and return the response within the .html file. HTML: <body> <form> ...

Utilizing an npm package within vscode with the .Vue framework: A step-by-step guide

After installing an npm package, I realized that it is written in JS while I am using the Vue framework. Even though Vue is based on JS, its syntax differs from traditional JS. How can I effectively integrate this package into my Vue project? I successful ...

Encountering a "Page Not Found" error while configuring Passport in Express 4

Struggling with integrating passport into my Node.js application. Despite rearranging my requirements in app.js, I'm unable to resolve the issue. The error message reads: Not Found 404 Error: Not Found at /home/salma/Desktop/my-project/app.js:5 ...

The extent of locally declared variables within a Vue component

Within this code snippet: <template> <div> <p v-for="prop in receivedPropsLocal" :key="prop.id" > {{prop}} </p> </div> </template> <script> export default ...