Create a multidimensional array from an array of objects

I am trying to organize my data by creating an array and listing each material based on its status. Here is the structure of my current array:

let data = [
        {
            Name: 'House 1', 
            Details:[
                {Materials: 'Door', Status: 'Delivered'},
                {Materials: 'Closet', Status: 'Pending'},
                {Materials: 'Chair', Status: 'Pending'},
                {Materials: 'Kitchen', Status: 'Delivered'},
                {Materials: 'Door Knob', Status: 'Delivered'}
            ]
        },

        {
            Name: 'House 2', 
            Details:[
                {Materials: 'Cabinet', Status: 'Delivered'},
                {Materials: 'Kitchen', Status: 'Delivered'},
                {Materials: 'Door', Status: 'Ongoing'},
                {Materials: 'Chair', Status: 'Ongoing'},
                {Materials: 'Window', Status: 'Cancelled'}
            ]
        },
        //Other codes here...
    ];

My goal is to display a breakdown of the status for each material in the expected output format shown below.

Expected Output:

[
    0: 'House 1'
        [
            0: 'Delivered': [ 0: 'Door', 1: 'Kitchen', 2: 'Door Knob' ]
            1: 'Pending': [ 0: 'Closet, 1: 'Chair' ]
        ]
    1: 'House 2'
        [
            0: 'Cancelled': [ 0: 'Window' ]
            1: 'Delivered': [ 0: 'Cabinet', 1: 'Kitchen' ]
            2: 'Ongoing': [ 0: 'Chair', 1: 'Door' ]
        ]
]
//where 0:, 1:, 2: represent the index of each nested array
//the indexes have been added similar to console.log output for reference but they are not mandatory in the final result

I have attempted to use forEach and .reduce methods, but I am encountering issues with my code execution. Your assistance in resolving this problem would be greatly appreciated :)

Answer №1

To accurately represent the desired structure, it is recommended to utilize objects instead of arrays for key-value pairs. A more effective approach would involve utilizing Array#reduce to organize elements based on their status within a single object.

let data=[{Name:"House 1",Details:[{Materials:"Door",Status:"Delivered"},{Materials:"Closet",Status:"Pending"},{Materials:"Chair",Status:"Pending"},{Materials:"Kitchen",Status:"Delivered"},{Materials:"Door Knob",Status:"Delivered"}]},{Name:"House 2",Details:[{Materials:"Cabinet",Status:"Delivered"},{Materials:"Kitchen",Status:"Delivered"},{Materials:"Door",Status:"Ongoing"},{Materials:"Chair",Status:"Ongoing"},{Materials:"Window",Status:"Cancelled"}]},];
let res = Object.fromEntries(data.map(o => [o.Name, o.Details.reduce((acc, curr) => {
  (acc[curr.Status] ??= []).push(curr.Materials);
  return acc;
}, {})]));
console.log(res);

Answer №2

The solution provided closely aligns with your requirements, utilizing arrays effectively.

let data=[
    {
        Name: 'House 1', 
        Details:[
            {Materials: 'Door', Status: 'Delivered'},
            {Materials: 'Closet', Status: 'Pending'},
            {Materials: 'Chair', Status: 'Pending'},
            {Materials: 'Kitchen', Status: 'Delivered'},
            {Materials: 'Door Knob', Status: 'Delivered'}
        ]
    },
    {
        Name: 'House 2', 
        Details:[
            {Materials: 'Cabinet', Status: 'Delivered'},
            {Materials: 'Kitchen', Status: 'Delivered'},
            {Materials: 'Door', Status: 'Ongoing'},
            {Materials: 'Chair', Status: 'Ongoing'},
            {Materials: 'Window', Status: 'Cancelled'}
        ]
    }
];
let newData=[];
for(let i in data){
    let delivered=data[i].Details.filter(e=>{if(e.Status==="Delivered")return true});
    let Pending=data[i].Details.filter(e=>{if(e.Status==="Pending")return true});
    let Ongoing=data[i].Details.filter(e=>{if(e.Status==="Ongoing")return true});
    let Cancelled=data[i].Details.filter(e=>{if(e.Status==="Cancelled")return true});
    let t=[data[i].Name,[],[],[],[]];
    for(let x in delivered){
        t[1].push(delivered[x].Materials);
    }
    for(let x in Pending){
        t[2].push(Pending[x].Materials);
    }
    for(let x in Ongoing){
        t[3].push(Ongoing[x].Materials);
    }
    for(let x in Cancelled){
        t[4].push(Cancelled[x].Materials);
    }
    newData.push(t);
}
console.log(newData);

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

Managing and Streaming Music in a Rails Application

Currently, I am storing mp3s using paperclip and they only play back if I utilize Amazon S3. However, I am hesitant to use Amazon S3 because I am unsure how to secure the files. Now, I am reconsidering my approach as I need to secure the mp3s and provide ...

The power of Swift combined with Firebase arrays

https://i.sstatic.net/Q1q0W.png I am facing an issue with appending values from JSON data and storing them in an array named 'values'. The goal is to retrieve these values in the 'updateChartValues()' function and add them to a new arr ...

Encountering a problem with loading ajax data in jVectorMap

I'm currently facing an issue where I am unable to load data from visitors into a map created using the jvectormap plugin. This problem is really frustrating me as I can't seem to fetch the data through ajax, although it works fine when I input ...

Detecting the failure of chrome.extension.sendRequest

Greetings Chrome Developers! I am wondering how one can determine when a chrome.extension.sendRequest call has not been successful. I attempted the following approach with no luck: chrome.extension.sendRequest({ /* message stuff here */ }, function(req){ ...

development session not persisting on local server (localhost:4200)

Currently, I am utilizing angular for the frontend and node.js along with express for the backend of my application. The interesting observation is that when I run the app on localhost:3000 (the designated port for the express app), everything operates cor ...

Attempting to invoke a function containing a promise in Javascript

Calling the function numberOfRedeems(dealId) from another function named setUpData raises an issue where the numberOfRedeems() function, which includes a promise and returns "counter", always returns as undefined when executed within the setUpData function ...

Using JavaScript to implement form authorization in ASP.NET Web API

I am looking to revamp a business application by utilizing asp.net web api as the service layer and implementing JavaScript to interact with the web api for retrieving and displaying data. While I have a good grasp on how all the scenarios will function s ...

Issues arise when submitting the form on a web page with an MVC 4 partial view, causing the page

Scenario: I am currently working on a C#/MVC 4 project where I have a view that includes a partial view. The main view consists of a form with a submit button, and the partial view is initially hidden but can be displayed by selecting a checkbox. Problem: ...

Is there a method to verify the presence of a message event listener already?

Is there a method to determine if a message event listener is already in place? I am trying to accomplish something similar to this: if(noMessageEventListenerExists) { globalThis.addEventListener('message', async function (data) {}) } I have ...

How can we identify all the foreign_key1 ids from a MySQL join table that have a specific foreign_key2 assigned to them that is within a specified list?

I have a scenario where I have two tables, Table A and Table B, connected by a many-to-many relationship. Table A: ID --- 1 2 3 Table B: ID --- 4 5 6 7 Table AB: ID | A_ID | B_ID ---------------- 8 | 1 | 4 9 | 1 | 5 10 | 1 | 6 11 | 1 | 7 ...

Customize the appearance of Woocommerce's blockUi feature with your

During an Ajax request, blockUI adds a style to the blocks of the checkout form and cart with "background: '#fff'". However, my entire website theme is black and I do not want the background color of the blocks to be white. Is there a way to remo ...

I am experiencing difficulty accessing links within my website using Node.js, Express.js, Webpack, Vue.js, and history mode without copying and pasting

Recently, I successfully launched a new website using Node.js, Express.js, and Vue.js with a router in history mode, all powered by Webpack. However, despite everything working smoothly with the express-history-api-fallback for my Single Page Application, ...

What steps can I take to make sure a particular node is successfully loaded and ready for use using JavaScript/jQuery?

When making a reservation at a hotel using the CJS Chrome extension, I am attempting to extract information about available rooms and rates both when the page loads and when the user changes dates. My current method involves injecting JavaScript into the p ...

Exploring error management in Vue3 and Vite when deploying to production

After following the error handler setup in the Vue documentation, I encountered a difference between using it on the development server and in production. The error handler effectively pinpointed the component and line number where the error occurred durin ...

Looking to display a div with both a plus and minus icon? Having trouble getting a div to show with left margin? Need assistance hiding or showing div text

Can someone please review this source code? Here is the demo link: http://jsfiddle.net/bala2024/nvR2S/40/ $('.expand').click(function(){ $(this).stop().animate({ width:'73%', height:'130px' }); $( ...

How can I implement Jquery ajax calls in various JavaScript functions?

I'm encountering an issue with a particular function in my code function readComm(){ $.post("something.php", {read:"read"}, function(data){ retVal = $.trim(data).toString(); console.log(retVal); return retVal; }); } T ...

Tips for deactivating the highlight on a previously selected menu item when clicking on the next menu option in Angular.js

In my pages, I have a menu where the landing page menu is initially highlighted. However, when I move to the next menu, the previous landing page highlight remains instead of being removed while swapping the menu. I am using Angular.js and angular ui-route ...

Eliminating Matching Elements from Pair of Numpy Arrays

I'm facing a seemingly simple question that I can't seem to find an answer for online. In my data, I have arrays of flux values and corresponding time values. While these two arrays are directly related (one flux value for each time value), some ...

Incorporating TypeScript with jQuery for efficient AJAX operations

I recently added jQuery typings to my TypeScript project. I am able to type $.ajax(...) without encountering any compile errors in VS Code. However, when I test it on localhost, I receive an error stating that "$ is not defined." In an attempt to address t ...