How to obliterate an array element in JavaScript

Hello everyone, I am faced with an array of objects that I need to destructure. Below is a snippet from the array:

[
  {
    "Area": "Werk Produktivität [%] - Target",
    "Jan": 86.21397507374327,
    "Feb": 86.0570021973368,
    "Mrz": 88.70898346258058,
    "Apr": 85.29801908413164,
    "May": 85.07431241640211
  },
  {
    "Area": "Werk Produktivität [%] - Actual",
    "Jan": 84.17054711398421,
    "Feb": 83.80826026601528,
    "Mrz": 84.11553769971036,
    "Apr": 83.76460916731,
    "May": 82.69773876702813
  }
]

My goal now is to split the array into the following sections:

[
  {
    "Area": "Werk Produktivität [%] - Target",
    "Jan": 86.21397507374327

  },
  {
    "Area": "Werk Produktivität [%] - Target",
    "Feb": 86.0570021973368,
   
  },
  ...

My initial approach was to utilize the ...rest parameter in this way, but it only retrieves the last 5 items of the array. Note that 'obj' represents the object excerpt displayed above.

const fn = ({ Area, ...rest }) =>
  Object.values(rest)
    .map(Month => ({
      Area,
      Month
    }))
       


})
const result = fn(obj)

Answer №1

If you want to achieve the same result, you can utilize the combination of reduce and Object.entries:

const info = [
  {
    "Area": "Productivity Area [%] - Target",
    "Jan": 86.21397507374327,
    "Feb": 86.0570021973368,
    "Mar": 88.70898346258058,
    "Apr": 85.29801908413164,
    "May": 85.07431241640211
  },
  {
    "Area": "Productivity Area [%] - Actual",
    "Jan": 84.17054711398421,
    "Feb": 83.80826026601528,
    "Mar": 84.11553769971036,
    "Apr": 83.76460916731,
    "May": 82.69773876702813
  }
]
const output  = info.reduce((result, {Area, ...remaining}) => {
  Object.entries(remaining).forEach(([key, value]) => result.push({Area, [key]: value}))
  return result
}, [])
console.log(output)

Answer №2

To create the desired object, you can utilize the Array.prototype.reduce function along with the Array.prototype.map function nested inside.

const arr = [  {    "Area": "Werk Produktivität [%] - Target",    "Jan": 86.21397507374327,    "Feb": 86.0570021973368,    "Mrz": 88.70898346258058,    "Apr": 85.29801908413164,    "May": 85.07431241640211  },  {    "Area": "Werk Produktivität [%] - Actual",    "Jan": 84.17054711398421,    "Feb": 83.80826026601528,    "Mrz": 84.11553769971036,    "Apr": 83.76460916731,    "May": 82.69773876702813  }];
const result = arr.reduce((a, {Area, ...months}) => {
  return [...a, ...Object.entries(months).map(([month, value]) => ({Area, [month]: value}))];
}, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Uncertain about the role of obj in the expression result = fn(obj) here. It seems like you are applying map to the array and extracting the first item from the resulting 2D array. Simply utilize flatMap on the array with fn as the callback function.

const output = inputArray.flatMap(fn)

or

const output = inputArray.map(fn).flat()

In addition, the function fn requires some adjustments. You should access the entries of the rest object as both the key and value are necessary.

Object.entries(rest)
      .map(([key, value]) => ({ Area, [key]: value }))

const input = [
  {
    "Area": "Werk Produktivität [%] - Target",
    "Jan": 86.21397507374327,
    "Feb": 86.0570021973368,
    "Mrz": 88.70898346258058,
    "Apr": 85.29801908413164,
    "May": 85.07431241640211
  },
  {
    "Area": "Werk Produktivität [%] - Actual",
    "Jan": 84.17054711398421,
    "Feb": 83.80826026601528,
    "Mrz": 84.11553769971036,
    "Apr": 83.76460916731,
    "May": 82.69773876702813
  }
]

const fn = ({ Area, ...rest }) =>
  Object.entries(rest)
    .map(([key,value]) => ({
      Area,
      [key]: value
    }))

const output = input.flatMap(fn)

console.log(output)

Answer №4

let data = [
  {
    "Area": "Sales Performance - Target",
    "Jan": 97.21465478124512,
    "Feb": 96.74215467984561,
    "Mar": 98.31245781321595,
    "Apr": 95.65985475125405,
    "May": 94.75814568754125
  },
  {
    "Area": "Sales Performance - Actual",
    "Jan": 95.25354874587412,
    "Feb": 93.58275478547821,
    "Mar": 95.97457845258715,
    "Apr": 92.78459854584578,
    "May": 91.48548745874154
  }
];

let newData = [];

for(entry of data){
  const {
    Area,
    ...monthlyData
  }=entry;
  for([month,value] of Object.entries(monthlyData)){
    newData.push({Area,[month]:value});
    
  }
}
console.log(newData);

I trust this information is beneficial to you!

Answer №5

If you want to achieve this task, you can utilize the concept of Destructuring assignment.

Here is a simple demonstration:

const data = [
  {
    "Area": "Werk Produktivität [%] - Target",
      "Jan": 86.21397507374327,
      "Feb": 86.0570021973368,
      "Mar": 88.70898346258058,
      "Apr": 85.29801908413164,
      "May": 85.07431241640211
  },
  {
    "Area": "Werk Produktivität [%] - Actual",
      "Jan": 84.17054711398421,
      "Feb": 83.80826026601528,
      "Mar": 84.11553769971036,
      "Apr": 83.76460916731,
      "May": 82.69773876702813
  }
];

const result = [];

data.forEach(item => {
    const { Area, ...restData } = item;
    Object.keys(restData).forEach(month => {
        result.push({ Area, [month]: restData[month] });
    });
});

console.log(result);

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

Substitution of "with" operator in strict mode

Let's say I have a user-entered string value stored in the variable f. For example: f = "1/log(x)"; In vanilla JavaScript, I used the following operator: f = "with (Math) {" + f + "}"; While this code worked perfectly fine in vanilla javascript, i ...

Adding data into a JSONB column by fetching information from a separate table in PostgreSQL

How can I insert into a JSONB column by selecting from a different table in PostgreSQL? I would like the JSONB insert to look like: {"name": "myname" ,"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4d0c1d7d0e4c3c9c5 ...

Master the art of navigating the Windows Sound Recorder with the power of JavaScript

I am creating a project that involves controlling the Windows sound recorder for tasks such as starting, stopping, and saving recordings. Is there a way to do this without displaying the recorder window? I would appreciate any assistance in solving this. ...

Converting XML to JSON in a Node.js application

I recently read an article on that explained the conversion process clearly, but unfortunately it's not working for me. Let me provide you with the code snippet: function parseXml(xml) { var dom = null; if (window.DOMParser) { try ...

Node.js allows you to seamlessly upload multiple images from various form fields or input types simultaneously

<form action="/upload-images" method="post" enctype="multipart/form-data"> <input type="file" name="image1" /> <input type="file" name="image2" /> <input type= ...

Showing information in Angular without using $scope

When working with Angular and angular UI-Router, my goal is to display content without relying on $scope. In my mainController, using directives like ng-repeat is no problem. However, I am struggling to access information from my postsController. Despite ...

Error: stripe.redirectToCheckout does not exist and cannot be executed

Can anyone help me with implementing Stripe checkout for a website? I've been struggling because the Stripe documentation is incomplete. Here's what I have so far: import React from 'react'; import { loadStripe } from '@stripe/stri ...

Teach me the steps in a promise chain to send a response and conclude the flow of the promise

Whenever I run the code below, I encounter this particular error message: Unhandled rejection Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client when result === null. 'use strict' const HttpStatus = require(&a ...

Manipulate Browser Navigation Behavior using JavaScript or AngularJS

How to Manage Browser Back Button Behavior Using AngularJS or JavaScript This is not a question, but rather a demonstration of how you can disable and manipulate the behavior of the browser's back button when using AngularJS or plain JavaScript. ...

Tips for parsing data arrays in HTML templates

I have three variables and I created an array where I pushed all these three variables in. In my HTML template, I am using a table. I tried using *ngFor but it is not working, and also attempted string interpolation which also did not work. Currently, I ...

Incorporate a string column from a JSON object array using T-SQL

I am looking to extract specific values from a nested JSON array and combine them into a single string to add as a column. My code resembles the following: DECLARE @json NVARCHAR(MAX) = N'[ { "id": 2, "info": { ...

Exploring the functionality of jQuery by incorporating a variable into the selector

I attempted to modify the src attribute of an image file using a variable, but it did not actually change. Can anyone pinpoint where I went wrong in using the variable? jquery var p2begen = "416"; $("[id=i'" + p2begen + "']").attr("src", "check ...

Using a child prop in React's map function

Initializing the parent component: class Parent extends React.Component { constructor(props) { super(props); this.state = { children: [ {name: "Julien Lennon"}, {name: "Sean Lennon"} ] } } render() { retur ...

What is the process for obtaining intersection set data from an array?

I'm trying to find the intersection set within an array only containing type 1 and 2. Can you help me with that? var arr = [ { id: 1, auths: [ { authId: 1, type: 1, value: 'Test1' }, { authId: 2, type: 1, ...

Shuffling the Highest Element with C++ Bubble Sorting

Currently, I am working on a school assignment that involves sorting an array in ascending order. However, I seem to be encountering difficulties with the bubble sorting method. While the array does begin to sort, the largest integer within the array is in ...

How to retrieve the current key from an array in PHP?

$arr = ( array('1231415'=>array('foo'=>'bar', 'test'=> 1)), array('32434'=>array('foo'>'bar', 'test'=> '0')), array('123244'= ...

A solution for accessing computed properties within a v-for loop

Currently, I am facing a challenge with the code provided below. It seems that computed properties do not support parameters. Do you happen to have any suggestions on how to overcome this issue? I am considering using watchers on functions but I am also ...

When using React and React Router v6, make sure to implement a 404 status code response for unmatched routes

When it comes to managing unmatched routes with React Router, I have a solid understanding: <Routes> {/* Public routes */} <Route exact path="/" element={<Home />} /> // Other routes... {/* Error routes */} ...

What is the outcome of XmlHttpRequest.responseText?

I am new to JavaScript and looking to explore the potential of XMLHttpRequest.responseText with a specified URL. Can someone guide me on how to efficiently test this? let url = "http://m.google.com/"; <br> let xmlHttp = new XMLHttpRequest(); <br& ...

Is there a way to retrieve the number of notifications that have not been seen or read from the API?

Is there a way to retrieve the unread or unseen count in PHP without relying on a real-time notifications JavaScript library? Typically, using a JavaScript library would provide the following information: "data": { "deleted": "array of activities or ...