What is the best way to divide an object key and transform it into an array of objects?

Currently, I am encountering an issue with converting an object into an array of objects. The object I have is structured as follows:

const employeeDetails = {
  "admin-name": "deepak",
  "admin-age": "29",
  "tester-name": "raju",
  "tester-age": "26",
};

The desired format is:

const employeeDetails = [
  {
    _id: "admin",
    name: "deepak",
    age: 29,
  },
  {
   _id: "tester",
   name: "raju",
   age: 26,
  },
];

Answer №1

Here is a way to achieve the desired output:

const teamDetails = {
  "leader-name": "Alice",
  "leader-age": "35",
  "member-name": "Bob",
  "member-age": "28",
}

const teamArray = Object
  .entries(teamDetails)
  .map(([key, value]) => {
    const [_id, attribute] = key.split('-')
    return {
      _id,
      [attribute]: value
    }
  })
  .reduce((acc, cur) => {
    acc[cur._id] ??= { _id: cur._id }
    Object.assign(acc[cur._id], cur)
    return acc
  }, {})

const finalResult = Object.values(teamArray)
console.log(finalResult)

Answer №2

const userDetails = {
  "user-name": "jessica",
  "user-age": "35",
  "user-role": "manager"
};

const formattedObj = Object.entries(userDetails).reduce(
  (accumulator, [key, value]) => {
    const dashIndex = key.indexOf('-');
    const parts = [key.slice(0, dashIndex), key.slice(dashIndex+1)];
    
    accumulator[parts[0]] ??= { id: parts[0] };
    accumulator[parts[0]][parts[1]] = value;
    return accumulator;
  }
, {});

const formattedArr = Object.values(formattedObj);

console.log(formattedArr);

Answer №3

const staffInfo = {
  "admin-name": "alex",
  "admin-age": "32",
  "tester-name": "jane",
  "tester-age": "28",
}

const processStaffRecords = (details) => {
  const recordsList = new Map();
  for (const [key, value] of Object.entries(details)) {
    const splitKey = key.split("-");
    if (splitKey.length === 2) {
      const recordItem = recordsList.get(splitKey[0]);
      if (typeof recordItem === "undefined") {
        const info = {
          _id: splitKey[0],
          [splitKey[1]]: value,
        };
        recordsList.set(info._id, info);
      } else {
        recordItem[splitKey[1]] = value;
      }
    }
  }
  return [...recordsList.values()];
};

console.log(processStaffRecords(staffInfo));

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

Specialized function to identify modifications in data attribute value

I have a container with a form inside, featuring a custom data attribute named data-av Here is how I am adding the container dynamically: > $("#desti_div").append("<div class='tmar"+count+"'><div > class='form-group col-md-6 ...

Looking to implement pyperclip functionality on Heroku platform

Is it feasible to utilize pyperclip on Heroku with a Selenium application in order to copy something to the clipboard? Since the platform utilizes a 'headless' browser and lacks a GUI, accessing the clipboard is challenging. Is there any way for ...

Is there a solution to fix the issue with IE causing hover effects not to

I'm currently in the process of designing a website, and I have implemented some image hover effects that reveal elements within the image when you hover over it. These effects are functioning correctly on Chrome, Safari, and Firefox; however, they ar ...

grab the destination URL from the embedded frame

Thank you for your attention. I am working with three iframes spread across different HTML documents. Here is how they are organized: In the file iframemain.html, there is: <iframe src="iframeparent.html" width="100%" height="600"> </iframe> ...

Java: Understanding how JSONObject inherits properties and methods from its

Struggling with object conversion to JSONObject (org.json.JSONObject) in Java. Issue arises when converting parent-child object X to JSONObject. Using "new JSONObject(this).ToString()" only includes the attributes of object X (child). Take a look at the ...

Invoke a PHP model function from JavaScript

I am looking to execute a php model function in an onclick attribute like shown below: HTML: <button id="my-button" onclick="setCookie()"></button> JS: function setCookie() { ... } PHP Model: Mage::getModel('core/cookie')-> ...

separate paths on a map into sections each measuring one unit

These are the given coordinates: coord = [(10,10), (13,10), (13,13)] Now, I am looking for new coordinates. The distance between two coordinates is always one unit. For example: (10,10) (11,10) (12,10) (13,10) (13,11) (13,12) (13,13) Any suggestions? ...

Extend the shelf life of cookies by utilizing AngularJS

I am currently implementing angularjs cookies in my project. https://docs.angularjs.org/api/ngCookies/service/$cookies Despite being aware of the security risks, I am using $cookies to store user credentials. I aim for the user to log in once and have th ...

Transform the infoBox into a jQuery dialog modal window

In this section, I have integrated a map with markers and infoBoxes. My goal now is to replace the infoBoxes with jquery dialog() and modal window functionalities. How can I achieve this effectively? Below is the code snippet that includes the implementat ...

Vue.js v-for dynamically creates HTML blocks that capture the state of collapse with two-way data binding

I am currently working on capturing the click action state within an HTML v-for generated block for a collapsible function. I have set up a data table and it seems that the state is being captured correctly. However, I am facing an issue where the displa ...

How to use JavaScript to toggle datalabels on Highcharts?

Is it possible to make Highcharts show datalabels for a specific category when clicking on the legend item? I've attempted to enable datalabels using the code below, but it hasn't worked: chart.series[0].data.dataLabels.enabled = true; You can ...

Looking for the child route parameter in Ember - A comprehensive guide

Consider having 2 routes: /products - displays a list of products -/:id - displays details of a specific product When a URL is provided for the above routes, the /products route must be able to access the /:id parameter in order to highlight that prod ...

What is the method for fetching the value from checkbox buttons in Bootstrap 4?

I am currently utilizing Bootstrap's button plugin for my buttons, specifically with 6 checkbox buttons. I am in need of a method to extract the value of each checked button in order to perform some calculations. However, I am struggling to find a sol ...

Rendering JSON Data in JavaScript using Table Pagination

Currently, I am working on rendering JSON data from a URL onto a table. My challenge is to display only 10 rows per page and I'm seeking guidance on how to achieve this. Below is the code snippet that I am using for rendering the data: const url = " ...

Arranging icons at the bottom of the post with a text box that changes dynamically

My challenge is that when the content in a box overflows, the box size increases and pushes the icons out of place. I want to ensure that the icons remain in a fixed position. This is how it currently looks: The comment, delete, and likes count end up on ...

Delete elements within an array

Imagine you have an array structured like this: $array = array( 'hello', 'world', 'lorem', 'ipsum', 'what', 'is', 'reality' ); Additionally, there is a string variable de ...

When examining the full response body in Postman, it is important to take into consideration the JSON DataSchema

As a newcomer to Postman, I am attempting to create an Automation Script for generating an object with JSON Schema. However, I have encountered an error that is proving difficult to overcome. Could someone kindly offer assistance? Below is the script res ...

What steps can be taken to ensure that events are triggered on the correct DIV element?

I am considering two different HTML structures for my project: <div id="threeJSContainer"> </div> <div id="UIControls"> <div ng-include src="'scripts/angular/UI.html'"></div> </div> When using the first c ...

Node JS - Fetching data using Busboy

I am currently facing a challenge with my NodeJS and Busboy project. I am attempting to extract all the variables from my router and pass them on to controllers. app.js (routes) router.post('/product', function (req, res) { var fields = {}; req ...

Should I use double or int for bubble sort?

Currently, I am in the process of developing a bubble sorting program to ensure that arrays are properly sorted. I have successfully compiled the first class, but I am facing issues with the second one. The error message indicates that the variable "dif" i ...