Arranging elements in an array based on two different properties

Trying to organize an array of elements (orders details).

https://i.stack.imgur.com/T2DQe.png

[{"id":"myid","base":{"brands":["KI", "SA"],"country":"BG","status":"new"}},{"id":"DEC-00500331","base":{"brands":["DEC"],"country":"UK","status":"new"},"psp":{"name":"adyen","status":"paid"}}]

An order can include items from different brands and is associated with a specific country website.

I am looking to group these orders by country and brand to create a consolidated list. Currently, I am able to group by country using the following code snippet:

let groupedDataByCountryAndBrand = _.groupBy(orders.value, 'base.country') 
Object.keys(groupedDataByCountryAndBrand).forEach(key => {
  table.push(
    {
      country : key,
      new : groupedDataByCountryAndBrand[key].filter( order => (order.base.status === SFCC_STATUS.new
      || SFCC_STATUS.open
      || SFCC_STATUS.completed )).length
    })
})

The desired outcome is to have a breakdown of newly created orders for each brand in a specific country. For example:

{
  "country" : "FR",
  "brand": "adidas",
  "pending": 4,
  "new" : 3,
  "an other status": 5
}

If you have any suggestions on how I can achieve this, please let me know. I am using lodash with a vue component. Thank you.

Answer №1

If you're seeking a solution without relying on additional libraries, consider the code snippet below:

const data = [{"id":"myid","base":{"orderNumber":"0500332","marketPlaceOrderCode":"","creationDate":"2022-06-14T10:49:10Z","source":"sfcc","brands":["KI", "SA"],"country":"BG","status":"new","totalEuro":12,"currency":"BGN","units":1,"coupons":null,"shipping":{"id":"BG01","name":"Speedy COD","status":"not_shipped"}},"psp":{"name":"payu","method":null,"status":null},"tms":null},{"id":"DEC-00500331","base":{"orderNumber":"id2","marketPlaceOrderCode":"&...

const rawResult = normalizeData(data);
console.log(makeItReadable(rawResult));

function normalizeData(data) {
  const result = {};

  data.forEach((order) => {
    const orderData = order.base;

    // add country to result (if not exists)
    if (!result[orderData.country]) {
      result[orderData.country] = {};
    }

    orderData.brands.forEach((brand) => {
      // add brand to exact country (if not exists)
      if (!result[orderData.country][brand]) {
        result[orderData.country][brand] = {};
    ...

  });

  return result;
}

function makeItReadable(rawData) {
  const readableResult = [];
  Object.keys(rawData).map((country) => {
    Object.keys(rawData[country]).map((brand) => {
      readableResult.push({country, brand, ...rawData[country][brand]});
    });
  });

  return readableResult;
}

This implementation will display the following outcome:

[
  { country: 'BG', brand: 'KI', new: 1 },
  { country: 'BG', brand: 'SA', new: 1 },
  { country: 'UK', brand: 'DEC', new: 1 }
]

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

Which specific transitionend (or animationend) event should I use for this application?

I'm feeling a bit lost when it comes to using transitionend (or if I should be using animationend in this scenario). I'm not sure whether to utilize var, node, or box. Essentially, I am a complete beginner in this case. My goal is to have my div ...

Setting the file type when uploading content: a step-by-step guide

When uploading a file to an S3 bucket, it's essential to identify the file extension and add the correct content type. $('#upload-files').on('click', function(e) { e.preventDefault(); var fileName = data.files[0].name; var ...

Design a model class containing two arrow functions stored in variables with a default value

I am looking to create a model class with two variables (label and key) that store functions. Each function should take data as an input object. If no specific functions are specified, default functions should be used. The default label function will retur ...

Even after applying trim() function, PHP's return statement still adds spaces unnecessarily

My function is supposed to return a boolean, but for some reason, it is adding spaces at the beginning of the string. Even after using trim(), the spaces persist. What could be causing this unexpected behavior? PHP function checkFile($v){ $result = is_ ...

Transforming an array of strings to integers within a GraphQL query when they are incorporated

I need help finding a solution to pass an array of strings and embed it into a query while using React and GraphQL. The issue I'm facing is that even though the parameter is accepted as an array of strings, it gets converted to a string when embedded. ...

What is the method for inserting JSON data into a select element's options?

Below is the HTML code snippet provided: <html> <head> <link rel="stylesheet" type="text/css" href="CarInfoStyle.css"> </head> <script src="CarInfoJavascript.js"></script> <body> <div class="search ...

How do you go about installing the most recent version of a module through Private NPM?

When using a private npm registry, I have noticed that some common commands do not seem to be functioning properly: npm install without specifying a specific @version :: issue npm outdated :: issue npm update :: issue npm view <private-packag ...

Instructions on allowing the user to enter text for searching through an array of objects, and displaying a message if a match is found. Use only pure JavaScript

As a newcomer to JavaScript, I greatly appreciate the support from everyone on this platform. Thank you in advance for your help! I am currently working on building a basic music app as a learning project in JavaScript. The main goal is to understand how J ...

Can anyone recommend a speedy sorting algorithm for an extensive list of objects in JavaScript?

Struggling to organize a large array of 2000 elements in ReactJS using JavaScript. The array includes: data = [ { index: 0, id: "404449", product_name: "ette", brand_name: "Dyrberg/Kern", base_pri ...

Is there a way for me to make this Select update when onChange occurs?

I am facing an issue with a react-select input that is supposed to display country options from a JSON file and submit the selected value. Currently, when a selection is made, the field does not populate with the selection visually, but it still sends the ...

Decode the JSON serialized format generated by CircularJSON

I have a JSON object in my node.js code that contains circular references. To send this information to the browser, I utilized the NPM package circular-json to stringify the object and serialize the circular references: var CircularJSON = require("circula ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...

Guide to generating a PDF file and utilizing a Node.js program for the download process

Seeking assistance in creating a button using my Node.js application to generate a downloadable PDF file filled with information from a PostgreSQL database. Any help is greatly appreciated! ...

The one-click button is functional on larger screens, while on mobile devices, only a double click will register

I am facing an issue in angular where a button works perfectly fine with one click on larger screens, such as Macbook. However, on iPhone, it requires a double click to function properly (it works fine on Android too). The alert triggers with a single cl ...

The material-ui library always registers Event.ctrlKey as true

When using the Table Component from the material-ui library, I encountered an issue with the multiSelectable feature. Setting the value of multiSelectable to true allows for multiple selections, but the behavior is not what I expected. By default, the sel ...

What are the steps to troubleshoot a Vue application?

I've encountered an issue with a code snippet that retrieves JSON data from a RESTful API. The code only displays the .container element and reports that the items array is empty, even though no errors are being shown. I attempted to debug the problem ...

Backbone sorting is specifically designed for organizing views within the framework

As I work on creating a sorting function in backbone, I have come across recommendations to use views to listen for changes in collections and then render the views once the collections are sorted. However, this approach does not suit my needs for two main ...

The Angular ViewportScroller feature appears to be malfunctioning in the latest release of Angular,

TestComponent.ts export class TestComponent implements OnInit, AfterViewInit { constructor( private scroller: ViewportScroller, ) {} scrollToAnchor() { this.scroller.scrollToAnchor('123456789'); } } HTM ...

Creating HTML elements with dynamic `routerLink` attributes in Angular 2

I have a model that references itself, as shown below. export class Entity { constructor(public id: number,public name: string,public children: Entity[]) { } } My goal is to create a tree list where each item has a routerlink. To achieve this, I ...

Retrieving a targeted data point from a JSON object

I am working with a json data that contains various properties, but I am only interested in extracting the uniqueIDs. Is there a way to retrieve ONLY the uniqueID values and have them returned to me as a comma separated list, for example: 11111, 22222? (I ...