How can you use JavaScript to convert a collection of Objects into a fresh Object set?

This inquiry has been presented in various formats, but I have yet to consolidate all the information in order to achieve the desired result. My apologies for reiterating what has already been addressed...

My objective is to transform an Array structure similar to this:

[
  0: { 
       2014: "6", 
       2015: "19",
       2016: "3",
       2017: "12",
       Name: "Jerry"
     },
  1: { 
       2014: "16", 
       2015: "9",
       2016: "",
       2017: "16",
       Name: "Bill"
     },
  2: { 
       2014: "", 
       2015: "2",
       2016: "43",
       2017: "7",
       Name: "Grace"
     }
]

To a format resembling this:

{
    "years": {
        "2014": {
            "Jerry": 6,
            "Bill": 16,
            "Grace": ""
        },
        "2015": {
            "Jerry": 19,
            "Bill": 9,
            "Grace": 2
        },
        "2016": {
            "Jerry": 3,
            "Bill": "",
            "Grace": 43
        },
        "2017": {
            "Jerry": 12,
            "Bill": 16,
            "Grace": 7
        }
    }
}

Here is a snippet of code that remains after numerous attempts and modifications:

For your information, the data is sourced from a CSV file loaded through D3.js csv()

let loadData = () => {
    return d3.csv(dataFile, function cb (err, d) {
        if (err) throw err;
        return d;
    });
};

loadData().get((err, n) => {
    if (err) throw err;

    let years = [];

    years.push(Object.keys(n[0]));

    years = _.flatten(years);
    years.splice(-1, 1);


    console.log(n[0]);

    n.map((x) => {
        console.log(Object.keys(x[0]));
    });

});

Answer №1

If you want to achieve this task, you can utilize the "reduce" method.

var dataset = [{
  2014: "6",
  2015: "19",
  2016: "3",
  2017: "12",
  Name: "Melissa"
}, {
  2014: "16",
  2015: "9",
  2016: "",
  2017: "16",
  Name: "Tom"
}, {
  2014: "",
  2015: "2",
  2016: "43",
  2017: "7",
  Name: "Linda"
}];

dataset = dataset.reduce(function(prev, item) {

  for (var prop in item) {
    if (prop === 'Name') {
      continue;
    }
    if (!prev[prop]) {
      prev[prop] = {};
    };

    prev[prop][item.Name] = item[prop];

  }
  return prev;
}, {});
dataset = {
  yearsData: dataset
};
console.log(dataset);

Answer №2

One possible solution is to loop through the array and keys to construct a new object.

var data = [{ 2014: "6", 2015: "19", 2016: "3", 2017: "12", Name: "Jerry" }, { 2014: "16", 2015: "9", 2016: "", 2017: "16", Name: "Bill" }, { 2014: "", 2015: "2", 2016: "43", 2017: "7", Name: "Grace" }],
    grouped = { years: {} };

data.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        if (k !== 'Name') {
            grouped.years[k] = grouped.years[k] || {};
            grouped.years[k][o.Name] = o[k];
        }
    });
});

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

Answer №3

To construct an object, you can utilize the `reduce()` method along with `Object.keys()` and a `forEach()` loop to dynamically add objects for each year.

var data = [{"2014":"6","2015":"19","2016":"3","2017":"12","Name":"Jerry"},{"2014":"16","2015":"9","2016":"","2017":"16","Name":"Bill"},{"2014":"","2015":"2","2016":"43","2017":"7","Name":"Grace"}]

var output = data.reduce(function(result, obj) {
  Object.keys(obj).forEach(function(key) {
    if(!result.years[key] && key != 'Name') result.years[key] = {}
    Object.assign(result.years[key] || {}, {[obj.Name]: obj[key]})
  })
  return result;
}, {years: {}})

console.log(JSON.stringify(output, null, 4))

Answer №4

If you are faced with this situation, one approach is to utilize the Array.prototype.reduce method. The first parameter of this method is a reducer function, and the second one is the initial value.

var data = [{
    2014: "6",
    2015: "19",
    2016: "3",
    2017: "12",
    Name: "Jerry"
  },
  {
    2014: "16",
    2015: "9",
    2016: "",
    2017: "16",
    Name: "Bill"
  },
  {
    2014: "",
    2015: "2",
    2016: "43",
    2017: "7",
    Name: "Grace"
  }
];

var result = data.reduce((accumulator, current) => {
  for (var key in current) {
    if (key !== 'Name') {
      accumulator.year[key] = accumulator.year[key] || {};
      accumulator.year[key][current.Name] = current[key];
    }
  }
  return accumulator;
}, {
  years: {}
});

console.log(result);

Answer №5

In some cases, reduce may not be necessary. Take this code snippet for example:

let data = { categories : {} };
for (let item of list) {
    for (let prop in item) {
        if (prop == 'Category') continue;
        data.categories[prop] = data.categories[prop] || {};
        data.categories[prop][item.Category] = item[prop];
    }
}

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

What is the best way to display the USD price in my JSON data?

I'm dealing with the following data [ { "id": "ethereum", "name": "Ethereum", "symbol": "ETH", "rank": "2", "price_usd": "449.935", "price_btc": "0.0574132", "24h_volume_usd": "1632850000.0", "market_cap_usd": " ...

Using Threejs JSONLoader and OOP to easily add models to a scene post-loading

I am working on incorporating the THREE JSONLoader into a "Scenemanager" Object that manages the addition and removal of objects and models. My main goal is to deepen my understanding of OOP, JS, and Threejs. Within App3D (which oversees the scene), I cal ...

Tips for correctly deciphering a JSON string that has been encoded using Html.Raw(Json.Encode(Model)):

Encoding model data into an HTML element can be done like this: @Html.Raw(Json.Encode(Model)); The resulting JSON string appears as follows: {"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo ...

Tips for generating JSON data in the correct format dynamically while continuously adding new information to the existing object

In my form, users input their email and password, which then generates dynamic JSON upon submission. However, I encountered an issue where the JSON gets corrupted when logging in with different user details as it updates the existing JSON with a new object ...

Using AngularJS to filter JSON data that is active

Below is the JSON data provided: [ { "Id": 10004, "PageName": "club", "active": "true" }, { "Id": 10040, "PageName": "qaz", "active": "false" }, { "Id": 10059, "PageName": ...

Troubleshooting Owl-Carousel Compatibility Issues in Javascript

I have been grappling with the implementation of a carousel on my website for 5 hours straight. The goal is to showcase multiple images while advancing the carousel by one image at a time. Following a YouTube tutorial (https://www.youtube.com/watch?v=nVNv1 ...

Loading data with limit offset in AngularJS can lead to controller functions crashing and causing data to become jammed

I have developed a video gallery application similar to Youtube using AngularJS. The application includes a REST API which is accessed through Angular services. There are two controller files in the application with similar functionalities but calling diff ...

Disable the default controls on the Open Layers Bing Map

I am currently working on an App that utilizes Geolocation with Open Layers to load a Bing Map Layer. My goal is to enable touch-based zooming and remove the default zoom buttons. Additionally, I would like to relocate the 'i' button to prevent a ...

Is there a Possible Bug with Highcharts Categories?

I am in the process of creating a dynamic sales dashboard that automatically updates a column chart displaying the latest sales figures for a team of agents. Within this project, I have developed a function called updateChart() which carries out the follo ...

Adding a fresh selection to the Bootstrap menu

I'm working on a straightforward Bootstrap form that includes a select input: <div class="form-group"> <label for="category" class="control-label col-sm-3">Category</label> <div class="input-group col-xs-8"> <sele ...

React encountered a 400 error when attempting to call a function in node.js

While attempting to call a registration endpoint from a React front-end to a Node.js back-end using Axios, I encountered a 400 error: http://localhost:9000/user/register 400 (Bad Request) Here is my code: /* React component for user registration */ impo ...

Unable to effectively translate placeholder text using i18next

I have set up a registration form with i18next on the server side. Here is my server-side configuration: var i18n = require('i18next'); i18n.init({ saveMissing: true, debug: true }); app.use(i18n.handle); Below is the content of my locale jso ...

"Learn how to update an existing table row and populate its cells with JSON data retrieved from a successful AJAX request without creating a

Currently, I am utilizing CouchCMS. The platform offers a feature known as repeatable regions which essentially generates tables to showcase recurring content. The defined repeatable region looks like this: <cms:repeatable name="item_detail" ...

Encountered an error when attempting to decode the JSON file using the default decoder in Python

url = 'https://www.magicbricks.com/property-for-sale/residential-real-estate?bedroom=&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment&cityName=Delhi-NCR' result = requests.get(url) data = result.json() I ...

Could somebody provide clarification on the functions being called in the Angular Test Code, specifically evaluate() and dragAndDrop()?

Exploring the drag and drop functionality of an angular-Gridster application using Protractor with a test code. I have some questions about the functions being used in the code snippet below. Can someone clarify the purpose of evaluate() - the API definit ...

Unravel the JSON data array and seamlessly add it to a MySQL database

Looking for some help here as I am struggling with extracting Json data and inserting it into a MySQL database using PHP. Any assistance would be greatly appreciated. {"CityInfo":[{"CityCode":"5599","Name":"DRUSKININKAI"},{"CityCode":"2003","Name":"KAUNAS ...

ASP.NET not functioning correctly in returning JSON errors

Currently, I am attempting to test an error in Json notation by making an ajax call. Below is my server method for this task: [System.Web.Services.WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string publishError() { ...

Is there a way for me to generate a button that directs users to a variety of pages?

How can I create a button that takes me to a random page on my basic website when clicked? I'm having trouble changing the "href" attribute so that it links to a specific page. This is the JavaScript code I've come up with: document.addEventList ...

React-Redux Countdown Timer Component

I recently created a JavaScript function in Symfony, but now I need to transfer it to React-Redux. However, as a beginner in React, I am struggling to make it work. Here is the issue I am facing: In my application, there is a list of cars parked in a par ...

Bidirectional data binding in AngularJS for <option> elements generated from an AJAX request

I have built a Controller called WebsiteController with the following functionality: JApp.controller('WebsiteController', function($scope, $resource) { var UsersService = $resource('/auth/users', {}); $scope.adding = false; ...