Updating the configuration of JavaScript array

As a newcomer to javascript, I am facing a minor issue. My goal is to restructure an array for use in rendering React Native using SectionList.

The JSON data I received from the Web API looks like this:

[
  {
    title: "Test",
    c: 1,
    d: 2,
  },
  {
    title: "Test",
    c: 3,
    d: 4,
  },
  {
    title: "Test",
    c: 5,
    d: 6,
  },
  {
    title: "Test01",
    c: 1,
    d: 2,
  },
  {
    title: "Test01",
    c: 3,
    d: 4,
  },
  {
    title: "Test01",
    c: 5,
    d: 6,
  },
  {
    title: "Test02",
    c: 1,
    d: 2,
  },
  {
    title: "Test02",
    c: 3,
    d: 4,
  },
  {
    title: "Test02",
    c: 5,
    d: 6,
  },
];

My objective is to transform this JSON structure into the following format:

[
  {
    title: "Test",
    data: [
      { c: 1, d: 2 },
      { c: 3, d: 4 },
      { c: 5, d: 6 },
    ],
  },
  {
    title: "Test01",
    data: [
      { c: 1, d: 2 },
      { c: 3, d: 4 },
      { c: 5, d: 6 },
    ],
  },
  {
    title: "Test02",
    data: [
      { c: 1, d: 2 },
      { c: 3, d: 4 },
      { c: 5, d: 6 },
    ],
  },
];

Answer №1

To simplify your data organization, consider linking it to the test name. However, if you prefer to map your array in a different way, you can achieve your desired outcome by following this approach:

let updatedArray=[];
originalArray.forEach(item => {
  let testName = item.title;
  let index = updatedArray.findIndex(a => a.title = testName);
  if (index === -1) {
    updatedArray.push({title}
    index = updatedArray.length - 1;
  }
let columns = ['c', 'd'];
let newData = {};
columns.forEach(col => {
 newData[col] = item[col];
});
if (!Array.isArray(updatedArray[index].data)) {
  isArray(updatedArray[index].data = [];
}
updatedArray[index].data.push(newData);
});

Answer №2

To obtain the desired format, you can use the reduce operation on the array.

const items = [
  {
    title: "Test",
    c: 1,
    d: 2,
  },
  {
    title: "Test",
    c: 3,
    d: 4,
  },
  {
    title: "Test",
    c: 5,
    d: 6,
  },
  {
    title: "Test01",
    c: 1,
    d: 2,
  },
  {
    title: "Test01",
    c: 3,
    d: 4,
  },
  {
    title: "Test01",
    c: 5,
    d: 6,
  },
  {
    title: "Test02",
    c: 1,
    d: 2,
  },
  {
    title: "Test02",
    c: 3,
    d: 4,
  },
  {
    title: "Test02",
    c: 5,
    d: 6,
  },
];

const formatted = items.reduce((carry, current) => {
    // creating a placeholder format to store the data 
    if(!carry.hasOwnProperty(current.title)) {
      carry[current.title] = {
        title: current.title,
        data: []
      };
    }
    // Adding the data to the unique title
    carry[current.title].data.push({ c: current.c, d: current.d });
    return carry;
}, []);
// formatted will contain key-value pairs
console.log(Object.values(formatted));

Answer №3

This custom function uses reduce to gather data into an array:

const originalData = [{
    name: 'Example A',
    value1: 1,
    value2: 2,
  },
  {
    name: 'Example A',
    value1: 3,
    value2: 4,
  },
  {
    name: 'Example A',
    value1: 5,
    value2: 6,
  },
  {
    name: 'Example B',
    value1: 1,
    value2: 2,
  },
  {
    name: 'Example B',
    value1: 3,
    value2: 4,
  },
  {
    name: 'Example B',
    value1: 5,
    value2: 6,
  },
  {
    name: 'Example C',
    value1: 1,
    value2: 2,
  },
  {
    name: 'Example C',
    value1: 3,
    value2: 4,
  },
  {
    name: 'Example C',
    value1: 5,
    value2: 6,
  },
];

const processedData = originalData.reduce((accumulator, {
  name,
  ...additionalData
}) => {
  const index = accumulator.findIndex((element) => name === element.name);
  if (index === -1) accumulator.push({
    name,
    details: [additionalData]
  });
  else accumulator[index].details.push(additionalData);
  return accumulator;
}, []);
console.log(processedData);

Answer №4

const data =[
  {
    name: "Sample",
    value1: 1,
    value2: 2,
  },
  {
    name: "Sample",
    value1: 3,
    value2: 4,
  },
  {
    name: "Sample",
    value1: 5,
    value2: 6,
  },
  {
    name: "Sample01",
    value1: 1,
    value2: 2,
  },
  {
    name: "Sample01",
    value1: 3,
    value2: 4,
  },
  {
    name: "Sample01",
    value1: 5,
    value2: 6,
  },
  {
    name: "Sample02",
    value1: 1,
    value2: 2,
  },
  {
    name: "Sample02",
    value1: 3,
    value2: 4,
  },
  {
    name: "Sample02",
    value1: 5,
    value2: 6,
  },
];
let resultData = {};
data.forEach((element)=>{
  if(!resultData[element.name]){
  resultData[element.name] = {info:[]};
}
  resultData[element.name]['info'].push({ value1: element.value1, value2: element.value2});
});
let newStructure =[];
Object.keys(resultData).forEach((key)=>{
  newStructure.push({
    name: key, info: resultData[key].info
})
});
console.log(newStructure)

Answer №5

const information = [
    {
      name: "John",
      age: 25,
      city: "New York",
    },
    {
      name: "Emily",
      age: 30,
      city: "Los Angeles",
    },
    {
      name: "Michael",
      age: 35,
      city: "Chicago",
    },
    {
      name: "Sarah",
      age: 22,
      city: "Miami",
    },
    {
      name: "David",
      age: 40,
      city: "Seattle",
    }
];

console.log('information', information);

function organizeData(information){
    let grouped = {}
    for(let person of information){
      if(grouped[person.city]){
          grouped[person.city].push({name: person.name, age: person.age})
      }else{
          grouped[person.city] ={
              details: [{name: person.name,age: person.age}]
          }
  
      }
    }
    
    console.log('grouped data', grouped)
    
  let finalResult = []
    for(let location in grouped){
      finalResult.push({city:location,details:grouped[location].details})
    }
    
    console.log('final result', JSON.stringify(finalResult))
    
  return finalResult
}

organizeData(information)

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 approach for writing a concise Select statement that produces a data list?

Currently, I am working on a small web application using Express.js and SQLite for local use. However, I am facing an issue when trying to perform a full select query on a table. All my scripts are written in JScript in 'use-strict' mode. I am a ...

Navigating through complex data structures of nested objects and arrays to selectively

I am currently working on a Vue project where I need to search through an array of nested objects to find a specific object based on the "title" property. The user interface includes a text input field for conducting the search operation. The structure of ...

Clouds marred by a unpleasant visual presentation

I've been following the instructions on this specific tutorial, but I'm attempting to scale it up significantly (increasing the radius to 100000 units). It seems like the size may be affecting the outcome, as the clouds in my earth render are ap ...

Is it possible to transform a ReadonlyArray<any> into a standard mutable array []?

At times, when working with Angular functions and callbacks, they may return a ReadonlyArray. However, I prefer using arrays in the traditional way and don't want to use immutable structures like those in Redux. So, what is the best way to convert a ...

Issues encountered when trying to retrieve data from an Express server

I have set up a NodeJS server with Express.js and I am attempting to send a request to it using fetch. fetch("http://localhost:3001/api", { method: "POST", headers: { "Content-Type": "application/json", ...

PyTorch: inverse lookup

I have 2 torch tensors x : Tensor, with dimensions K y: Tensor, with dimensions L Where all values in y are arranged in ascending order and unique (although not every value in x is necessarily found in y) I am searching for an efficient method to generat ...

Multer is successfully retrieving images, but unfortunately, it is failing to save the files in the intended directory

I am currently facing an issue with my Express server. The problem arises when a user attempts to make a post request for their profile, including a profile picture submission. I have set up Multer to handle the image upload process and store the photo in ...

Show a different image with a matching title each time the page loads

I need help creating a JavaScript script that will display a random image from an array along with an associated title each time the page loads. Is there a way to do this without using an onload function placed in the body tag? Currently, my code relies o ...

Tips for importing and exporting icons in a way that allows for dynamic importing using a string parameter

I am facing an issue with dynamically importing SVG icons in React Native. Initially, I tried using the following code snippet: const icon = require(`@src/assets/icons/${iconName}`) However, after realizing that this approach wouldn't work for me, I ...

Is it possible to include 'file.php' along with the 'id' using php?

I have constructed my website using php include and the structure of the index is as follows: Menu.php (menu system) main.php (Main page) footer.php (footer section) On the main.php (main page), I have incorporated a news script that utilizes $_GET t ...

Sending File from React to Express Causes 404 Error

My current project setup involves a React application housed in a client folder and an Express server located in the root directory. Within the React app, there are functionalities for selecting files and submitting them. I aim to transfer these files from ...

Is there a way for me to open this tr link in a separate tab rather than in the current one?

Is there a way to open this link in a new tab? <a href="....." target="_blank"> This is how it can be done using JavaScript: <script> $(document).ready(function(){ $('table tr').click(function(){ window.open($(this).att ...

How to showcase an ArrayList with and without organizing it?

Similar Question: Why is my Sorted ArrayList not displaying properly? Sample Code Snippet: String header1 = "Initial Order\n\n"; String header2 = "Sorted Order\n\n"; String myList = ""; for (int i = 0; i < collectionLi ...

Assign updated values to a list based on changed fields in the map

In order to track the modified fields and display them to the user, I need to identify which key corresponds to the changed field and create a new key-value pair for user visibility. log: [ 0: {type: "Changed", fields_changed: Array(2), date_modificat ...

An easy way to attach a Contextmenu to a specific element

I have implemented a scrolling feature for one of the div elements in my Application. Inside this div, there is a templated table with over 100 rows. Users are able to add or delete rows using a contextMenu. The contextMenu offers 4 options - AddTop, AddB ...

Issues with the functionality of the ObjectMapper.readValues() method when handling invalid JSON data

Working on a project that heavily utilizes Jackson, I decided to delve deeper into understanding the workings of the readValue() method for specific scenarios. To conduct my experiment, I created an intentionally empty inner class: static class Empty { ...

Sending the value of a selected option from the view to the controller in .NET 6 using a for loop

When I populate a view with a list of employees and shifts in the view model, I use a for loop to iterate through the dates and select lists for both employees and shifts. However, when I submit the form, the model only captures the first selection instead ...

Restrict the number of requests made to the Facebook graph_url_engagement_count API

Encountering the following error message: "(#613) Calls to graph_url_engagement_count have exceeded the rate of 10 calls per 3600 seconds." I am looking for a way to ensure that my API calls for a specific link stay within the limit. Please note that the ...

What is the best way to divide my value sets using jQuery?

Within a given string such as 28_34/42/34,23_21/67/12,63_5/6/56, I am seeking to split or eliminate sets based on the ID provided. For example, if the ID is 23, then the set 23_21/67/12 should be removed. To achieve this, I am checking the value after the ...

Error: Python requires string indices to be integers

Whenever I attempt to iterate over JSON using the code below, I encounter the error message TypeError: string indices must be integers. I have searched through numerous threads for a solution but have not been successful so far. This excerpt showcases the ...