Breaking Down An Array of Objects Using JavaScript

I am facing an issue with splitting/separating objects within an array. I know how to do it for a single object, but the challenge arises when dealing with an array of objects. The array structure is as follows:

[
    {
        "KPI": "Productivity [%] - Target",
        "Area": "Plant",
        "Jan22": 0.8621397507374327,
        "Feb22": 0.8605700219733681,
        "Mrz22": 0.8870898346258058
        
      },
      {
        "KPI": "Productivity [%] - Target",
        "Area": "Assembly",
        "Jan22": 0.8817383050990651,
        "Feb22": 0.8856950523200521,
        "Mrz22": 0.9267495852228734
        
      },
      {
        "KPI": "Productivity [%] - Target",
        "Area": "Assembly CYU",
        "Jan22" : 0.8984342053383161,
        "Feb22": 0.9285678969440421,
        "Mrz22": 0.9625283644615115
       
      }
]

My goal is to split each object as shown below:

[
    {
        "KPI": "Productivity [%] - Target 0 ",
        "Area": "Plant",
        "Month": 0.8621397507374327
      },
      {
        "KPI": "Productivity [%] - Target 1 ",
        "Area">: "Plant",
        "Month": 0.8605700219733681
      },
      {
        "KPI": "Productivity [%] - Target 2 ",
        "Area": "Plant",
        "Month": 0.8870898346258058
      }
      
      {
        "KPI": "Productivity [%] - Target 0 ",
        "Area": "Assembly",
        "Month": 0.8817383050990651
      },
      {
        "KPI": "Productivity [%] - Target 1 ",
        "Area": "Assembly",
        "Month": 0.8856950523200521
      },
      {
        "KPI": "Productivity [%] - Target 2 ",
        "Area": "Assembly",
        "Month": 0.9267495852228734
      }
      
      {
        "KPI": "Productivity [%] - Target 0 ",
        "Area": "Assembly CYU",
        "Month": 0.8984342053383161
      },
      {
        "KPI": "Productivity [%] - Target 1 ",
        "Bereich": "Assembly CYU",
        "Month": 0.9285678969440421
      },
      {
        "KPI": "Productivity [%] - Target 2 ",
        "Area": "Assembly CYU",
        "Month": 0.9625283644615115
      }
]

I have attempted using the following code snippet:

Ausgabe2 = [];
 obj = 
        {
                "KPI": "Productivity [%] - Target",
                "Area": "Plant",
                "Jan22": 0.8621397507374327,
                "Feb22": 0.8605700219733681,
                "Mrz22": 0.8870898346258058
                
              },
              {
                "KPI": "Productivity [%] - Target",
                "Area": "Assembly",
                "Jan22": 0.8817383050990651,
                "Feb22": 0.8856950523200521,
                "Mrz22": 0.9267495852228734
                
              },
              {
                "KPI": "Productivity [%] - Target",
                "Area": "Assembly CYU",
                "Jan22": 0.8984342053383161,
                "Feb22": 0.9285678969440421,
                "Mrz22": 0.9625283644615115
               
              }
        
        
        
    const fn = ({ KPI, Area, ...rest }) =>
      Object.values(rest)
        .map(Month => ({
          KPI,
          Area,
          Month
        }))
    
    const result = fn(obj)
    
    for (var i =0; i < result.length; i++){
      obj2 = {
        
        KPI : result[i].KPI + " " + i,
        Bereich: result[i].Area,
        Month : result[i].Month , 
         
        
      }
      Ausgabe2.push(obj2);
    }
       

   console.log(Ausgabe2);

However, I am not getting the desired output illustrated earlier. Instead, the current output is:

[ { KPI: 'Productivity [%] - Target 0',
    Bereich: 'Plant',
    Month: 0.8621397507374327 },
  { KPI: 'Productivity [%] - Target 1',
    Bereich: 'Plant',
    Month: 0.8605700219733681 },
  { KPI: 'Productivity [%] - Target 2',
    Bereich: 'Plant',
    Month: 0.8870898346258058 } ]

How can I modify the code to achieve the desired output?

Answer №1

To achieve the desired outcome, my recommendation would be to utilize Array.flatMap() in combination with Object.values().

The approach involves creating an entry for each month and appending the month index to the KPI string. Once flattened, the result should align with the expected format.

const data = [ { "KPI": "Productivty [%] - Target", "Area": "Plant", "Jan22": 0.8621397507374327, "Feb22": 0.8605700219733681, "Mar22": 0.8870898346258058 }, { "KPI": "Productivty [%] - Target", "Area": "Assembly", "Jan22": 0.8817383050990651, "Feb22": 0.8856950523200521, "Mar22": 0.9267495852228734 }, { "KPI": "Productivty [%] - Target", "Area": "Assembly CYU", "Jan22": 0.8984342053383161, "Feb22": 0.9285678969440421, "Mar22": 0.9625283644615115 } ]

const result = data.flatMap(({ KPI, Area, ...months }) => { 
    return Object.values(months).map((Month, idx) => {
        return { KPI: KPI + ` ${idx}`, Area, Month};
    })
})

console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }

Answer №2

Based on the details provided, it appears that the fields KPI and Area are consistent across all entries. You can easily loop through the array and divide each data point into its corresponding months.

const entries = [{
    "KPI": "Productivty [%] - Target",
    "Area": "Plant",
    "Jan22": 0.8621397507374327,
    "Feb22": 0.8605700219733681,
    "Mar22": 0.8870898346258058

  },
  {
    "KPI": "Productivty [%] - Target",
    "Area": "Assembly",
    "Jan22": 0.8817383050990651,
    "Feb22": 0.8856950523200521,
    "Mar22": 0.9267495852228734

  },
  {
    "KPI": "Productivty [%] - Target",
    "Area": "Assembly CYU",
    "Jan22": 0.8984342053383161,
    "Feb22": 0.9285678969440421,
    "Mar22": 0.9625283644615115

  }
]

const months = new Set(["Jan22", "Feb22", "Mar22"]);
const formattedEntries = [];

for (let entry of entries) {
  for (let field in entry) {
    if (months.has(field)) {
      formattedEntries.push({
        "KPI": entry["KPI"],
        "Area": entry["Area"],
        [field]: entry[field]
      });
    }
  }
}

console.log(formattedEntries)

Answer №3

let data = [
  {
    "Metric": "Productivity [%] - Target",
    "Location": "Plant",
    "Jan22": 0.8621397507374327,
    "Feb22": 0.8605700219733681,
    "Mar22": 0.8870898346258058
  },
  {
    "Metric": "Productivity [%] - Target",
    "Location": "Assembly",
    "Jan22": 0.8817383050990651,
    "Feb22": 0.8856950523200521,
    "Mar22": 0.9267495852228734
  },
  {
    "Metric": "Productivity [%] - Target",
    "Location": "Assembly CYU",
    "Jan22": 0.8984342053383161,
    "Feb22": 0.9285678969440421,
    "Mar22": 0.9625283644615115
  }
];

const processedData = data.map(({ Metric, Location, ...months }) => {
  return Object.values(months).map((Month) => {
    return { Metric, Location, Month };
  });
}).flat();
console.log(processedData);

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

Just diving into JavaScript, what makes jQuery so powerful?

As a newcomer to javascript (although functional programming is no problem for me), I find myself questioning some of the design choices made by jQuery. Is it too late to make changes now, or are they simply too ingrained in the framework? For example, the ...

Leveraging JavaScript to extract data from a JSON file upon clicking a button

Currently, I am working on a problem where the user enters values into a search box, clicks the search button, and then with the onClick event, the search terms are compared to values in a JSON file. I do not have knowledge of jQuery, so if there is a solu ...

Is AngularJS Service a Singleton for Your Application?

As a relative newcomer to angularJS, I've learned that services should be singleton, but for some reason it's not working for me. Here is my service: .factory('TrainingPlan', function($http, SERVER){ var o = { exercises: [], ...

Display information from a specific identifier in a modal popup window after clicking a button using PHP and MySQL

When a button is clicked on my website, a popup window appears using modal functionality. The issue I am facing is not being able to retrieve the correct data based on the id of the button. Below is the HTML table code snippet: <tbody> <?php $cou ...

Recording the usernames of users in an array by utilizing the Userid feature in discord.js version 13

I am currently working on creating a field called "ReqUsers" in the object "commandInformation". I am trying to make it check if the message.author has the necessary permissions and/or roles, or if the message.author.id is included in the list of users spe ...

Ways to address circular references in JSON serialization stemming from bidirectional Many-to-Many mappings in Hibernate

When trying to convert a POJO to JSON, I encountered an issue with circular references. While I am familiar with handling one-to-many and reverse relationships using annotations like @JsonBackReference and @JsonManagedReference, I am struggling with bidire ...

What is the best way to extract the class name from ui.item or event using the function(event, ui)?

Is there a way in jQuery to extract the class name from a function with two parameters, event and ui? For example, consider the following code snippet: $(document).tooltip({ show: null, position: { my: "left top", at: "left bottom ...

Is it possible to achieve a seamless interaction by employing two buttons that trigger onclick events to alternately

I have a specific goal in mind: I want to create two buttons (left and right) with interactive cursors. The left button should initially have a cursor of "not-allowed" on hover, indicating that it cannot be clicked at the beginning. When the right button ...

Error: The validation process failed due to missing information. The file name and path are both required for validation

In my current project, I am attempting to upload a file from the frontend to the backend and save it. However, I am encountering an error that looks like this: Error The error message is as follows: this.$__.validationError = new ValidationError(th ...

Prevent Page Refresh with F5 in Silverlight

Many of the users on my platform are accidentally hitting the F5 key while typing, causing them to lose all their work. I don't want to completely block the ability to refresh the page. I attempted using the following JavaScript solution, however it ...

Utilizing AJAX to submit a combination of text fields and files in an HTML form

Just starting out with AJAX and JQuery, I'm curious if it's possible to send data from an HTML form, including a text file and two separate text boxes, via an AJAX request. So far, I've managed to send the data from the text boxes but not th ...

Pairing TMDb genre IDs and their respective names using JavaScript within the Ember.js framework

If you've ever worked with the TMDb (The Movie Database) api for movies, you might have encountered this issue. I am struggling to display the genre names for each movie shown. My goal is to replace the numbers in genre_ids from the movies api with th ...

Using a C# byte array as an argument for a C function that accepts a char

Currently, I am developing a C library called cROS and I am facing an issue where I need to retrieve a byte[] from C# in order to share it using the library. The problem arises when trying to pass a byte[] to a char*. Below is the C# code snippet: [DllIm ...

Displaying numerous Google charts within a Bootstrap carousel

A bootstrap carousel has been implemented to showcase our company's data. The carousel includes a bootstrap table, images, and two Google charts: a pie chart and a stacked bar chart. The issue arises when the active class is not maintained for the Go ...

Guide on how to verify your identity with a SAML relying party by utilizing a Web Application as a client

I've been exploring this topic for quite some time now, but haven't had much success. Here's the scenario: 1. Logging in to a Web Application using standard form authentication. 2. Logging in from the Web Application to a SAML Relying Party ...

Python - locating a word in a string using index

I am seeking a fast and effective method to convert an index in a string to the word at that index. Consider the following string: This is a very silly string If, for example, the index I have is 7, the desired output should be very. Similarly, if the ...

Occasional TypeError when receiving JSONP response using jQuery .ajax()

Occasionally, I encounter an error message stating Uncaught TypeError: undefined is not a function when processing the JSONP response from my jQuery .ajax() call. The JSON is returned successfully, but sometimes this error occurs during the reading process ...

Tips for transferring data between pages in VUE js using paths

I currently have two pages - an add page and an edit page. I am looking to transfer data from the edit page to the add page. When the save button is clicked in the edit page, it should redirect the user back to the add page with a URL of /test/admin/testin ...

Can someone guide me on the process of adding a personalized emoji to my discord bot?

After creating my own discord bot, I'm ready to take the next step and add custom emojis. While tutorials have helped me understand how to use client.cache to type an emoji, I'm unsure of how to upload them and obtain their ID for use in my bot. ...

Is there a way to customize the primary column in Material-table?

I am utilizing the Material-table and I am in need of rearranging the column index to be at the end of the table as the default position for this column (actions) is at the beginning. Here is the code snippet for the table: <MaterialTable title=" ...