Simplify an array for utilization in D3

Currently working on extracting data from mongoDB using javascript and React. In order to utilize D3.js effectively, I need to flatten the array.

Presently, my data looks like this:

[{
        "location": [ { "createdAt": "2023-04-03T18:27:42.088Z" } ],
        "count": 2,
        "item": [ { "name": "football" } ]
},{
        "location": [ { "createdAt": "2023-04-03T18:27:42.088Z" } ],
        "count": 1,
        "item": [ { "name": "Baseball" } ]
}]

Desired format for D3.js visualization:

[{
        "createdAt": "2023-04-03T18:27:42.088Z",
        "count" : 2,
        "name": "football" 
    },{
        "createdAt": "2023-04-03T18:27:42.088Z",
        "count": 1,
        "name": "baseball"
    }]

Attempted iterating through objects but encountered some issues:

{
0.item.0.name:  "baseball"
0.count: 1
0.location.0.createdAt: "2023-04-03T18:27:42.088Z"
1.etc...
}

Tried using:

console.log(array.flatMap((element) => element).flat()) ;

Unfortunately, this approach did not yield the desired outcome.

Answer №1

To simplify the data structure, you can utilize the map function along with destructuring:

const info = [
  {
    "location": [{ "dateCreated": "2024-05-12T09:13:22.093Z" }],
    "quantity": 3,
    "object": [{ "type": "pen" }]
  },
  {
    "location": [{ "dateCreated": "2024-05-12T09:13:22.093Z" }],
    "quantity": 1,
    "object": [{ "type": "pencil" }]
  }
];

const simplifiedData = info.map(({ location: [{ dateCreated }], quantity, object: [{ type }] }) => ({
  dateCreated,
  quantity,
  type
}));

console.log(simplifiedData);

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

I attempted to host my MERN stack application on a shared hosting platform, but encountered the error message stating "Unable to obtain lock for the application."

I am attempting to deploy a MERN stack application on shared hosting, but I encounter an error message when trying to run NPM INSTALL or stop my app. The error reads "Can't acquire lock for an app." https://i.stack.imgur.com/52g3n.png ...

The componentDidMount function is not initializing the state

I am trying to access the references from the render function and then set them to the state. Below is my code snippet: class App extends Component { constructor(props) { super(); this.arr = this.generateTimelineArray(); ...

Verify a roster within a display by utilizing annotations

My solution involves using a listbox to display a list as shown below, and I am also utilizing Chosen.js to allow for selecting multiple records. @Html.ListBox("AllLanguages", new SelectList(ViewBag.Languages, "Id", "Language1")) <div id="languagesDi ...

Selecting a particular item in a list depending on time using JavaScript, jQuery, or Angular

When working with a JSON file and binding it to list items, I have included a name/value pair in the json for each line indicating audio time, such as "time like 0, 5, 10 in seconds form". In my Cordova application, I am using a media plugin and implement ...

Steps for presenting the information from the book

My current project involves creating an ebook using NodeJS, MongoDB, and Express. Right now, I am able to display all the chapters as a simple list, as shown in Fig. 1. However, I also want to include subchapters, where users can click on a chapter and vie ...

Obtaining Texture Map coordinates from an Object's surface in Three.js

Seeking a solution for mapping a 3D object in Three.js to a point on its surface and finding the corresponding point on a texture file using x,y coordinates. Currently, I am using raycasting to locate points on the object's face, each of which should ...

What is the best way to extract the last JSON object from a JSONArray based on a specified value

I am currently working with a JSONArray that looks like the following: [ { "id": 1, "firstName": "abc", "isActive": true }, { "id": 2, "firstName": "cde", "isActive": false }, { " ...

Shorten a data point in JSON code

I'm currently in the process of developing a stock widget that utilizes JSON to retrieve data from the Yahoo API/YQL console. I am specifically working with values extracted from the key ChangePercentRealtime, however, the values are longer than what ...

Is the return type determined by the parameter type?

I need to create an interface that can handle different types of parameters from a third-party library, which will determine the return type. The return types could also be complex types or basic types like void or null. Here is a simple example demonstra ...

Interactive Map Displayed within a Pop-up Window

Recently, I developed a custom Google map where points are plotted and an HTML popup window appears when the image is clicked. Now, my goal is to open a file with JavaScript functions inside a lightbox/fancybox when a user clicks on an image. Below is th ...

What is the best way to modify specific data retrieved from an API using Angular?

After successfully listing some data from an API using ngFor, I am facing an issue with editing the data. Whenever I click the edit button, it edits the entire data instead of just the specific row. Below is the code snippet for reference: HTML <table ...

DoubleClicking on Checkbox Causes jQuery Click Event to Trigger Twice

Experimenting with DataTables, I have created a table setup like this: <table id='dt'> <thead><!-- Some Header --></thead> <tbody> <tr data-lineid=1> <td><input type=' ...

Manual bootstrapping in AngularJS 1 is ineffective

I am a beginner with angularjs. I attempted to create 2 separate modules in a single js file and then manually bootstrap one of them to an element. This method was suggested in a stackoverflow post. However, it seems to not be working. Each of the modules ...

why is the sum coming out as an undefined number?

My challenge involves creating a table that should display the total price, however, it keeps showing NaN. The code snippet below outlines how the total price is calculated: import React from 'react'; const Total = (props) => { const {ite ...

Iterate through the array and append information

My challenge involves working with an array named "content". Within this array, there is the "asin-id," which serves as a product ID. My goal is to iterate through the content array, retrieve the specific product associated with the asin-id, add the produc ...

What is the most effective method for transforming a space-separated list of classes into a jQuery selector?

Is there a quick and efficient method for converting a space-separated list of classes like: classOne classTwo classThree into a selector such as: $('.classOne .classTwo .classThree') I am considering utilizing either a loop to construct a se ...

What is the proper syntax for adding a shard to a MongoDB database with authentication enabled?

My current challenge involves adding a shard to mongos using the sh.addShard command. I'm following the documentation provided at this link: https://docs.mongodb.com/v3.4/tutorial/add-shards-to-shard-cluster/. Here is the example from the documentatio ...

Implementing a jQuery method in a PHP page that is loaded through AJAX

I am facing an issue on my page where I am using jquery/ajax to load a series of buttons into a div. This script loads buttons every time the user scrolls the page and each button should run a jquery function when clicked. The problem arises when I switche ...

What is the best way to verify if a class attribute includes a specific class or not?

Below is the code snippet provided. The code fetches all classes and then checks for the presence of the 'mat-checked' class. pmanage.no_additional_cost().last().invoke('prop', 'class').then((Class) => { let ...

Execute jQuery load function once all other AJAX requests have finished

I am facing an issue with a jQuery .each loop that iterates through an array and makes AJAX calls for each item. The goal is to reload part of the page using the .load() method once all AJAX calls are complete. However, implementing the .ajaxStop() method ...