Converting a JavaScript hash into a single object: A step-by-step guide

I have an array of objects in the following format:

var log=[
{
  billkey:"Name",
  billvalue:"ABC"
},
{ 
  billkey:"Department",
  billvalue:"Computer"
}];

and I want to convert it into a single object like this:

var log={
       "Name":"ABC",
       "Department":"Computer"
     };

I attempted the following approach:

for(var i=0;i<log.length;++i){
   pushToAry(log[i].billkey, log[i].billvalue);
}

function pushToAry(name, val) {
 var obj = {};
 obj[name] = val;
 ary.push(obj);
 }

However, this results in pushing a new object into the array every time, leading to:

var ary =[
    0:{
      "Name":"ABC"
    },
    1:{ 
      "Department":"Computer"
    }];

How can I properly convert this array of objects into a single object?

Answer №1

One great feature of ES6 is its simplicity:

let newObject = {};

for (let {key, value} of data)
    newObject[key] = value;

For those who prefer a more "functional" approach:

let newObject = Object.assign(...data.map(item => ({[item.key]: item.value})))

Answer №2

One way to extract information from an array of objects and return it as a new object is by using the reduce() method.

var data = [{
  key: "Name",
  value: "John"
}, {
  key: "Age",
  value: 30
}];

var result = data.reduce((acc, obj) => (acc[obj.key] = obj.value, acc), {});
console.log(result)

Answer №3

If you're looking to implement a loop, here's a simple way to do it:

var userDetails = [
  {
    attribute: "Name",
    value: "John"
  },
  {
    attribute: "Age",
    value: 25
  }];
  var userInfo = {};
  userDetails.forEach(item => userInfo[item.attribute] = item.value);
  console.log(userInfo);

Answer №4

If you want to simplify the process, you can utilize Array.prototype.reduce method in JavaScript to condense it into the desired object as shown in the example below:

var items=[{key:"Name",value:"John"},{ key:"Department",value:"HR"}];

var result = items.reduce(function(previous,current){
  previous[current.key] = current.value;
  return previous;
},{})

console.log(result);

Answer №5

let resultObject = {};
for (let index = 0; index < log.length; index++)
    resultObject[log[index].billkey] = log[index].billvalue;

To start, I create an empty object to hold the results. Then, I loop through the log array and for each entry, I retrieve the key (log[index].billkey) and value (log[index].billvalue) of the log record. These values are then used to add a new property to the result object: obj[...key...] = ...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

The event "subscriptionRemoved" is not being triggered when a password change is made on the Microsoft Graph API

Utilizing the Microsoft Graph API, I have set up subscriptions to receive notifications for calendar events through Node.js. As per the guidelines outlined in the documentation on Enhancing notification reliability for Outlook resources (preview), it speci ...

What is the best way to arrange the keys of a JavaScript object in a customized

I am struggling to find a way to custom sort a JavaScript object properly. For example, I have the following object: var test = { 'yellow': [], 'green': [], 'red': [], 'blue': [] } And an array with values ...

Is there a way to create a navigation menu that highlights as we scroll down the page?

Check out this example of what I am looking for. https://i.stack.imgur.com/fdzvZ.png If you scroll, you will notice that the left menu highlights. Sub-menus will extend when the corresponding menu is highlighted and collapse when other menus are highlig ...

Tabs within the AutoComplete popup in Material-UI

Would it be feasible to showcase the corresponding data in the AutoComplete popover using Tabs? There could be potentially up to three categories of data that match the input value, and my preference would be to present them as tabs. Is there a way to in ...

PHP object representing a datetime in JSON format

How can I convert a JSON datetime object sent to JavaScript into a JavaScript datetime object? The PHP return is: "date": { "lastErrors": { "warning_count":0, "warnings":[], "error_count":0, "errors":[] }, "timezone": { "nam ...

Using Switch Case and If Statements in Javascript and Jquery

Can you help me troubleshoot this code? It's designed to detect clicks and keypress events within the #ts_container div for buttons and anchors. The goal is to use an If statement in each case to determine if it's a click or keypress, then update ...

Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column: receiptsByDate: function(){ let byDate = _.groupBy(t ...

What should I do to resolve the issue of the function if ($(window).width() < 768) {} not functioning properly upon resizing the browser?

I am working on a functionality where the navigation bar items will toggle hidden or shown only when the browser width is less than 768px and an element with the class "navlogo" is clicked. I have included my code below for reference. if ($(window).width( ...

Can a pledge be honored at a precise moment?

I have implemented transitions on my web page. When clicked, everything fades out to an opacity of 0 over a duration of 1 second. Then, a new page is swapped in and everything fades back in to an opacity of 1 over another 1-second duration. The issue aris ...

Tips for serving images locally instead of using an online URL when exporting with Next.js static:

I've encountered an issue where multiple images pulled from an online source are not being included in my export when I start the process. The image URLs are stored as strings online, but I want them to be saved locally and exported that way instead o ...

Having trouble debugging JavaScript as a beginner? Unable to pull the cookie value and use it as a variable? Let's

Hello everyone, I'm new to coding and have been working on a project. However, I am facing some errors and need help debugging. I have a cookie named "country" with a value of "AZ" that I want to retrieve using JavaScript and use it in my Google Maps ...

What is the best way to streamline the if statement in JavaScript?

Here is the given code snippet: public noArtistBeingEdited(): boolean { if (this.isFirstNameBeingEdited()) { return false; } if (this.isLastNameBeingEditable()) { return false; } return true; } What are some ways to ma ...

``There was an issue with the connection while fetching data using Nextjs middleware

I've encountered an issue where this code works perfectly fine in dev mode but fails when switched to production mode. Can anyone help me figure out what's causing the fetch failure? export default async function middleware(req: NextRequest) { ...

Updating choices within a div in real-time by changing the select box dynamically

I need to swap out the select box that is nested inside this div <div class="models"> <select disabled="disable"> <option>Model Name</option> </select> </div> I am attempting to target the div and manipul ...

The error message "ReferenceError: $ is not defined" is displayed within

My current requirement involves loading templates within an iframe, and to achieve this, I have implemented the following code: <div class="col m8 l8 s12 margin-top-30" id="hue-demo-bg-div"> <iframe id="myiframe" src="/themes/{{$themeid}}.ht ...

When a link is right-clicked, the window.opener property becomes null

Currently, I am utilizing the window.opener property in JavaScript to update the parent window from a child window. The parent window simply consists of a table with data and a link to open the child window. When the child window is launched, a JavaScript ...

Incorporating an offset with the I18nPluralPipe

Having trouble with my multiselect dropdown and the text pluralization. I attempted to use the I18nPluralPipe, but can't seem to set an offset of 1. ListItem = [Lion, Tiger, Cat, Fox] Select 1 Item(Tiger) = "Tiger", Select 3 Item(Tiger, Cat, Fox) = ...

Swagger is unable to locate a user schema when utilizing Yaml files

Hello, I am a beginner using Swagger and trying to create simple endpoint documentation. However, I am facing an issue with my schema type and cannot figure out what's wrong. To start off, I organized my folder structure in the root src directory whe ...

Is it possible to utilize the map method to extract objects that are nested multiple layers deep?

I am working on accessing the change order information in order to compile a list of all the change_order_names. The code I am currently using is yielding the results displayed below. Could someone assist me in understanding how to access the change order ...

The reason behind a loop being caused by an IF statement

Here is a snippet of code that I'm trying to understand: ReactDOM.render(<Change />, document.getElementById('app')); function Change() { const [i, setI] = React.useState(0); let rnd = 9; if (i !== rnd) { setTime ...