combine the values from various keys into one cohesive array

Here is an array of objects that I need to manipulate:

[
  {
    "name": "product1",
    "Jan": 3,
    "Feb": 2,
    "Mar": 0,
    "Apr": 1,
    "May": 3,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  },
  {
    "name": "product2",
    "Jan": 4,
    "Feb": 0,
    "Mar": 0,
    "Apr": 1,
    "May": 1,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  }
]

I want to create a new array with just the data values in the correct month order for each product like this:

[
  {
    "name": "product1",
    "data": [3, 2, 0, 1, 3, 0, 0, 0, 5, 0, 0, 0],
  },
  {
    "name": "product2",
    "data": [4, 0, 0, 1, 1, 0, 0, 0, 5, 0, 0, 0],
  }
]

Any suggestions on how to achieve this?

Answer №1

To extract the name, you can use the map function and then retrieve the remaining values by applying Object.values():

var items = [ { "name": "item1", "Jan": 3, "Feb": 2, "Mar": 0, "Apr": 1, "May": 3, "Jun": 0, "Jul": 0, "Aug": 0, "Sep": 5, "Oct": 0, "Nov": 0, "Dec": 0 }, { "name": "item2", "Jan": 4, "Feb": 0, "Mar": 0, "Apr": 1, "May": 1, "Jun": 0, "Jul": 0, "Aug": 0, "Sep": 5, "Oct": 0, "Nov": 0, "Dec": 0 }];

var output = items.map(({name,...rest})=>({ name, data : Object.values(rest)}));

console.log(output);

Answer №2

Utilize a map function to loop through an array of objects. Extract the name field from the remaining entries and create a new object containing just the name and the rest of the data (using Object.values()).

var items = [ { name: "item1", Jan: 3, Feb: 2, Mar: 0, Apr: 1, May: 3, Jun: 0, Jul: 0, Aug: 0, Sep: 5, Oct: 0, Nov: 0, Dec: 0 }, { name: "item2", Jan: 4, Feb: 0, Mar: 0, Apr: 1, May: 1, Jun: 0, Jul: 0, Aug: 0, Sep: 5, Oct: 0, Nov: 0, Dec: 0 } ];
var resultArray = items.map(element => {
  let { name, ...remainingData } = element;
  return { name, data: Object.values(remainingData) };
});
console.log(resultArray);

Answer №3

const products = [{
    "name": "product1",
    "Jan": 3,
    "Feb": 2,
    "Mar": 0,
    "Apr": 1,
    "May": 3,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  },
  {
    "name": "product2",
    "Jan": 4,
    "Feb": 0,
    "Mar": 0,
    "Apr": 1,
    "May": 1,
    "Jun": 0,
    "Jul": 0,
    "Aug": 0,
    "Sep": 5,
    "Oct": 0,
    "Nov": 0,
    "Dec": 0
  }
];

function extractData(products) {
  let result = [];
  for (let i = 0; i < products.length; i++) {
    result[i] = {};
    result[i].name = products[i].name;
    result[i].data = [];
    for (let month in products[i]) {
      if (month !== "name") {
        result[i].data.push(products[i][month]);
      }
    }
  }
  return result;
}

console.log(extractData(products));

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

Using TypeScript to interpret JSON - insert a 'data' label

Consider the following example of a JSON structure: [ { "id":1, "position":3, "articleNumber":"ServiceElement" }, { "id":2, "position":2, "articleNumber":"ServiceElement" } ] Is there a way to transfo ...

The function this.props.array.map is not defined

Currently, I am in the process of learning React and have been attempting to display an element for each user in a predefined array. However, upon testing, my browser keeps throwing an error stating that this.props.users.map is not a function. I have imple ...

AngularJS application encountering an undefined variable within the scope

I'm attempting to set a Boolean property on an element within my array object that is part of my scope. When I use the code below and try to set tasks[id].deleted = true, I encounter the following error: angular.js:12798 TypeError: Cannot set proper ...

Differences between ClosureFeedbackCellArray and FeedbackVector in the V8 engine

Can you explain the distinction between ClosureFeedbackCellArray and FeedbackVector within V8? What steps are necessary to initiate the shift from ClosureFeedbackCellArray to FeedbackVector? What is the significance of the InterruptBudget attribute found ...

Utilize JavaScript to compel image caching

I've run into an issue where I am trying to duplicate a randomly generated image, but despite using the same URL, a different image is being loaded every time. This problem has been confirmed in both Chrome and Firefox browsers. Unfortunately, since ...

Display the text of the checked checkboxes in a dropdown menu option

How can I display the selected checkbox's text inside the button? Currently, when I select something from the checkbox, it only shows the text "Multiple Selection ▼" <div class="dropdown show"> &l ...

Empty array returned when using fetch in a for loop

Currently, I am developing a server route to execute API calls. I have encountered the need to make two separate fetch requests as I require additional information that is not available in the first fetch. The issue lies in declaring a variable outside o ...

Is it necessary for me to use NG-IF / NG-SWITCH or should I opt for NG-SHOW & NG-HIDE instead?

I'm facing a frustrating dilemma because I am unsure of the best approach to take in this scenario. Below is the basic setup: I aim to display the current status of a movie, which will have different messages in the DOM based on its state. A movie ca ...

Challenges with AES encryption

I am currently working on a project that requires encrypting a String with AES. The program must be capable of taking in a String and producing an encrypted string in hex format along with a key, or utilizing a user-specified key and string to output unenc ...

Struggling to find a solution for changing the color of a select box when an option is chosen

Here's an example of the HTML I'm working with: <select onclick="colorchanger()"> <option name="white" value="0">--Select--</option> <option name="red" value="1">Work</option> <option name="green" value="2" ...

What is the purpose of incorporating helper text into textField MUI for yup validation in our project?

<TextField label="Password" type="password" onBlur={handleBlur} onChange={handleChange} value={values.password} name="password" ...

What is the best way to format table values as currency?

Still getting the hang of Javascript, and I'm in the process of learning... Currently, my challenge involves calculating the total sum of values within a Bootstrap 4 table and formatting the result as currency (specifically in USD format). While I&ap ...

Rows of JSON arrays - Utilizing OPENJSON

Having just ventured into the world of Json in SQL, I find myself utterly frustrated by this situation I currently have a table [AuditEntries] dedicated to storing audit changes for entities in a json array CREATE TABLE #AuditEntries( [Id] [bigint] I ...

Exploring the depths of JSON structures with Vue.js

I'm facing a bit of a challenge with a rather complex JSON file (output of elasticsearch engine) that I want to parse using Vue. I've successfully parsed the JSON and accessed different values in it, but I'm struggling with parsing an array ...

Dynamically access nested objects by utilizing an array of strings as a pathway

Struggling to find a solution for accessing nested object properties dynamically? The property path needs to be represented as an array of strings. For example, to retrieve the label, use ['type', 'label'] I'm at a roadblock wit ...

What steps can I take to ensure that I establish the definition of this variable?

My situation involves a variable called Blog, which is a mongoose model. The definition of this variable is as follows: db.once("open", function(){ var userSchema = new mongoose.Schema({ username: String, password: String }); ...

How to retrieve the image source using jQuery

<img src="../img/arnold.png" alt="Arnold"> Is there a way to retrieve the absolute path of this image using jQuery? Currently, when I use img.attr("src"), it only returns "../img/arnold.png", but I need it to return something like "http://site.com/ ...

Run JavaScript function after form submission in Oracle Application Express

Looking for suggestions on how to control the order of function execution? In my work with Oracle APEX, I've set up a button labeled "export" that captures the ROWID of selected rows in an interactive grid and passes these values to a page item. The ...

Variable not defined, scope problem

Currently, I am attempting to modify the state of an object within an array in React by utilizing Immutability Helpers. handleChange = (itemInput, itemNum = null) => event => { this.setState({ rows: update(this.state.rows, { itemNu ...

Can a Javascript file be concealed from view?

Imagine a scenario where the localhost root file is served an HTML file using the following code: app.get('/', (req, res) => res.sendfile('index.html')) Is it possible to include JavaScript files in the HTML document that are not a ...