Tips for constructing a multi-dimensional entity from an existing object?

Looking to frame an object as a two-dimensional entity.

let data = [
            {'id':1, 'price':'12', 'price_type':'abc', 'mode':1, 'year':1},
            {'id':1, 'price':'22', 'price_type':'def', 'mode':1, 'year':1},
            {'id':1, 'price':'15', 'price_type':'abc', 'mode':1, 'year':2},
            {'id':1, 'price':'32', 'price_type':'def', 'mode':1, 'year':2},
            {'id':1, 'price':'30', 'price_type':'abc', 'mode':1, 'year':3},
            {'id':1, 'price':'35', 'price_type':'def', 'mode':1, 'year':3}
           ];

The desired output is:

{mode:{year:{'abc_price':price1, def_price:price2}}

For example:

 results = {
             1:{
                1:{'abc_price':12, def_price:22},
                2:{'abc_price':15, def_price:32},
                3:{'abc_price':30, def_price:35}
              } 
            }

How can I achieve the above result with the provided object? Your assistance is greatly appreciated.

I attempted the following approach:

let tmpArr = [];
let objArr = {};

for(let i = 0; i < data.length; i++) {
        objArr[data[i].mode][data[i].year] = {'mode': data[i].mode, 'year': data[i].year};
         if(data[i].price_type == "abc") {
              objArr[data[i].mode][data[i].year]['abc_price'] = data[i].price;
        }
        if(data[i].price_type == "def") {
             objArr[data[i].mode][data[i].year]['def_price'] = data[i].price;
        }
      tmpArr.push(objArr);
}

console.log("temp Array: "+ JSON.stringify(tmpArr));

An error was encountered due to an undefined index value in a two-dimensional array.

Answer №1

A different approach involves utilizing the reduce function to categorize the entities.

var obj_example = [{    'id': 1,    'price': '12',    'price_type': 'abc',    'mode': 1,    'year': 1  },  {    'id': 1,    'price': '22',    'price_type': 'def',    'mode': 1,    'year': 1  },  {    'id': 1,    'price': '15',    'price_type': 'abc',    'mode': 1,    'year': 2  },  {    'id': 1,    'price': '32',    'price_type': 'def',    'mode': 1,    'year': 2  },  {    'id': 1,    'price': '30',    'price_type': 'abc',    'mode': 1,    'year': 3  },  {    'id': 1,    'price': '35',    'price_type': 'def',    'mode': 1,    'year': 3  }],
    results = obj_example.reduce((a, {mode, year, price, price_type}) => {
      a[mode] = (a[mode] || {});
      a[mode][year] = (a[mode][year] || {});  
      a[mode][year][`${price_type}_price`] = price;  
      return a;
    }, {});

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

Answer №2

If you want to group objects based on certain keys and create a new object with the price value, you can iterate through the objects and array of keys for grouping.

var items = [{ id: 1, price: '12', price_type: 'abc', mode: 1, year: 1 }, { id: 1, price: '22', price_type: 'def', mode: 1, year: 1 }, { id: 1, price: '15', price_type: 'abc', mode: 1, year: 2 }, { id: 1, price: '32', price_type: 'def', mode: 1, year: 2 }, { id: 1, price: '30', price_type: 'abc', mode: 1, year: 3 }, { id: 1, price: '35', price_type: 'def', mode: 1, year: 3 }],
    groups = ['mode', 'year'],
    output = items.reduce((result, item) => {
        groups.reduce(
            (target, key) => target[item[key]] = target[item[key]] || {},
            result
        )[item.price_type + '_price'] = item.price;
        return result;
    }, {});

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

Answer №3

It seems that your sample data is not correctly formatted as JSON, it should be an array. Here is a suggested solution:

obj_sample = [{'id':1, 'price':'12', 'price_type':'abc', 'mode':1, 'year':1},
        {'id':1, 'price':'22', 'price_type':'def', 'mode':1, 'year':1},
        {'id':1, 'price':'15', 'price_type':'abc', 'mode':1, 'year':2},
        {'id':1, 'price':'32', 'price_type':'def', 'mode':1, 'year':2},
        {'id':1, 'price':'30', 'price_type':'abc', 'mode':1, 'year':3},
        {'id':1, 'price':'35', 'price_type':'def', 'mode':1, 'year':3}]
let resultObj = {};
obj_sample.forEach(obj => {
    resultObj[obj.mode] = resultObj[obj.mode] || {};
    resultObj[obj.mode][obj.year] = resultObj[obj.mode][obj.year] || {};
    resultObj[obj.mode][obj.year][`${obj.price_type}_price`] = obj.price;
});
console.log(resultObj);

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

Deactivate Date Field for Editing Orders in WooCommerce

Is there a way to deactivate the Date Created textbox on the Edit Orders page of Woocommerce? I attempted to use pointer-events: none; but unfortunately, it did not have any effect. I am seeking a method to disable the Date Created field. https://i.sstat ...

What is the best method to merge duplicate arrays based on their values using PHP?

Consider the following example array: $myArr1 = array( "word1" => "hello", "word2" => "hi", "word3" => "welcome", ); $myArr2 = array( "word1" => "hello", "word3" => "welcome", "word2" => "hola" ); Is there a way to combine duplicate ke ...

I am experiencing difficulties with decoding the JSON in Appengine ProtoRPC

For some reason, I'm having trouble getting the protoRPC API to work on my app-engine. Here is the request I am making: $.ajax({ url: '/guestRPC.get_tags', type: 'POST', contentType: 'application/json', ...

Refresh an AngularJS table built with Bootstrap to display live data in real-time through the use of ng-repeat

Utilizing a bootstrap table with ng-repeat to populate data, yet encountering issues updating and displaying the table. A custom directive has been created for drag and drop functionality in AngularJS. When a file is dragged and dropped, the information i ...

A guide on combining two native Record types in TypeScript

Is it possible to combine two predefined Record types in TypeScript? Consider the two Records below: var dictionary1 : Record<string, string []> ={ 'fruits' : ['apple','banana', 'cherry'], 'vegeta ...

What is the solution for the error message "Unhandled Runtime Error" with the description "TypeError: videoRef.current.play is not a function"?

I am currently working on implementing custom controls for a video on a Nextjs website. When using a standard HTML <video> component, the code functions as expected and clicking the custom play button successfully plays the video. However, when I swi ...

What is the proper way to utilize the ES6 import feature when using a symbolic path to reference the source file?

I am seeking a deeper understanding of the ES6 import function and could use some assistance. The Situation Imagine that I have a portion of code in my application that is frequently used, so I organize all of it into a folder for convenience. Now, in t ...

Receiving JSON data in TypeScript and displaying it in a structured table format

I am just starting to learn TypeScript, I need to be able to handle JSON data of varying sizes... Once I receive the data, I want to display it in a table format... The structure of my JSON data will resemble this: [{"regionID":1 "regionname":"Can"}, ...

tips for accessing variables within app.get

Is there a way to make a variable or a set of variables inside app.get accessible throughout the entire project? I am working on capturing information from an SMS text message, organizing it into the "messageData" variable, and then sending it to the "Mess ...

Calculating the number of days left within a month using dayjs

Currently, I'm facing a challenge that seems to have no easy online solution, and if there's one thing I find particularly frustrating; it's dealing with dates. My current task involves calculating a person's age in months and days. Fo ...

What is the best way to save a Firebase user's unique identifier in a React application?

In the process of developing a React web application, I am focusing on allowing users to register using their email and password. Once registered, each user will have access to their profile information. I have outlined my Firebase data structure below: ...

Converting PHP arrays into JavaScript arrays with the help of json_encode()

Is there a way to pass an array from PHP to the JavaScript function console.log()? I'm currently simulating a database and need help with this specific task. Despite not having an array declared in my code, I attempted to use the .getJSON() function w ...

Combine all elements into a single array using the map method in JavaScript

In my possession, I have an array of objects with IDs and names: [ { "id": 10, "name": "comedy" }, { "id": 12, "name": "documentary" }, { ...

Hide the search results if the user leaves the input field blank

I am trying to implement Live Search JSON Data Using Ajax jQuery, and I want to be able to search through multiple JSON files. When the page initially loads with an empty input field, no results are displayed. However, if you type and then delete text in ...

Update the specific component according to the identified modifications

In my project, I have two simple components: parent and child. The parent component contains an Array and for each element in the array, it renders the child component. parent.component.ts export class parent implements OnInit { data: CustomType[] = [ ...

Mastering the Art of Page Scrolling with d3

I would like to implement a scrolling effect for my d3 that allows the entire page to scroll while panning, similar to the effect on challonge (http://challonge.com/tournaments/bracket_generator?ref=OQS06q7I5u). However, I only want the scrolling to occur ...

Utilizing the code plugin in conjunction with Popcorn.js

I am currently exploring the world of Popcornjs and attempting to utilize the code plugin. However, I am facing some challenges in implementing it successfully. After following this example and managing to get the video to play, I found myself unable to e ...

The data values are transformed following a JSON AJAX POST request with a percentage symbol

I'm facing an issue while developing a slide editor using AJAX. I have a PHP script with multiple functions that can be accessed via different GET parameters. Everything works smoothly until I try to save the slides, at which point the value of transf ...

Is it possible to include a JavaScript script in a Laravel Blade file?

I have an Auth module from nwidart/laravel-Module. I am trying to include a script file in the Modules\Auth\Resources\views\layouts\app.blade.php file, like this: <body> ...... ... <!-- Scripts --> <script s ...

Disable the spinning animation of the Bootstrap spinner to keep it still and static

I am currently utilizing bootstrap 4 for my project. When a particular event starts, I have successfully managed to make the spinner spin with the code snippet below: <span class='spinner-border spinner-border-sm text-primary' role='statu ...