Analyzing JSON and organizing arrays with multiple values into groups

In my JSON response, the structure is as follows:

{
  data: [
    {
      attributes:[
        {
          type: 'size',
          value: '10'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '10'
        },
        {
          store_id: '2000',
          stock: '3'
        },
        {
          store_id: '3000',
          stock: '5'
        }
      ]
    },
    {
      attributes:[
        {
          type: 'size',
          value: '9'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '10'
        },
        {
          store_id: '2000',
          stock: '3'
        },
        {
          store_id: '4000',
          stock: '5'
        }
      ]
    },
    {
      attributes:[
        {
          type: 'size',
          value: '7'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '19'
        },
        {
          store_id: '2001',
          stock: '8'
        },
        {
          store_id: '4000',
          stock: '2'
        }
      ]
    }
  ]
}

With JavaScript, I am attempting to extract and sort the values based on store ID.

For example:

Considering the above data, here is what I aim to achieve:

array['2000'] = ['10 - (3)', '9 - (3)', '7 - (8)']

Here, 2000 represents the store_id and array values are in the format size - (stock).

Answer №1

A straightforward approach involves utilizing Array#reduce to consolidate your data.

Additionally, ensure that within each inventory, all items are merged to accurately define the value with the correct structure such as

${attributes[0].value} - (${stock})

const yourJson = {data:[{attributes:[{type:'size',value:'10'},{type:'colour',value:'red'}],inventory:[{store_id:'1000',stock:'10'},{store_id:'2000',stock:'3'},{store_id:'3000',stock:'5'}]},{attributes:[{type:'size',value:'9'},{type:'colour',value:'red'}],inventory:[{store_id:'1000',stock:'10'},{store_id:'2000',stock:'3'},{store_id:'4000',stock:'5'}]},{attributes:[{type:'size',value:'7'},{type:'colour',value:'red'}],inventory:[{store_id:'1000',stock:'19'},{store_id:'2001',stock:'8'},{store_id:'4000',stock:'2'}]}]};

const result = yourJson.data.reduce((acc, {attributes, inventory}) => 
{
  for(const {store_id, stock} of inventory){
    acc[store_id] = acc[store_id] ||[];
    acc[store_id].push(`${attributes[0].value} - (${stock})`);
  }
  
  return acc;
}, {});

console.log(result);

Answer №2

If you need to choose an item from the inventory, consider using the reduce() method.

Take a look at this example:

let response = {
  data: [
    {
      attributes:[
        {
          type: 'size',
          value: '10'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '10'
        },
        {
          store_id: '2000',
          stock: '3'
        },
        {
          store_id: '3000',
          stock: '5'
        }
      ]
    },
    {
      attributes:[
        {
          type: 'size',
          value: '9'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '10'
        },
        {
          store_id: '2000',
          stock: '3'
        },
        {
          store_id: '4000',
          stock: '5'
        }
      ]
    },
    {
      attributes:[
        {
          type: 'size',
          value: '7'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [
        {
          store_id: '1000',
          stock: '19‘
        },
        {
          store_id: '2001',
          stock: '8'
        },
        {
          store_id: '4000',
          stock: '2'
        }
      ]
    }
  ]
}

let selected_inventory = response.data.reduce((a, b) => a = b.inventory.find(inv => inv.store_id === '2000') || a, {})
console.log(selected_inventory) // The expected outcome is { "store_id": "2000", "stock": "3" }

Answer №3

The previous response may not present the solution in the exact format you are seeking.

function convertToObjects(arr) {
  const objList = {};

  for (const { attributes, inventory } of arr) {
    // Make sure there is always a "size" attribute
    const size = attributes.find(attr => attr.type === 'size').value;

    for (const inv of inventory) {
      // Create an array if it doesn't exist
      objList[inv.store_id] = objList[inv.store_id] || [];

      // Generate and add the final strings
      objList[inv.store_id].push(size + ' - (' + inv.stock + ')');
    }
  }
  
  return objList;
}

const givenData = {
  data: [{
      attributes: [{
          type: 'size',
          value: '10'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [{
          store_id: '1000',
          stock: '10'
        },
        {
          store_id: '2000',
          stock: '3'
        },
        {
          store_id: '3000',
          stock: '5'
        }
      ]
    },
    {
      attributes: [{
          type: 'size',
          value: '9'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [{
          store_id: '1000',
          stock: '10'
        },
        {
          store_id: '2000',
          stock: '3'
        },
        {
          store_id: '4000',
          stock: '5'
        }
      ]
    },
    {
      attributes: [{
          type: 'size',
          value: '7'
        },
        {
          type: 'colour',
          value: 'red'
        }
      ],
      inventory: [{
          store_id: '1000',
          stock: '19'
        },
        {
          store_id: '2001',
          stock: '8'
        },
        {
          store_id: '4000',
          stock: '2'
        }
      ]
    }
  ]
}

console.log(convertToObjects(givenData.data));

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 causes duplicate packages to appear in Bower at times?

There appears to be two identical packages available for the Sugar javascript library, sugar and sugarjs. Are these packages interchangeable or are they being maintained separately by different individuals? ➔ bower info sugarjs bower sugarjs#* ...

Passing data between Vue components

Currently, I am extracting a language setting from the DOM and assigning it to a global Vue.js variable in the following manner: const language = document.querySelector('html').getAttribute('lang'); Vue.prototype.$language = language; ...

Triggering a jQuery ajax request upon pressing a key on the keyboard

When a user inputs text into an <input> element, I'm using ajax to send a request to the server. Here's how it looks: $('#my-input').bind("input", function(event){ // ajax request code }); My concern is that too many requests ...

Encountered an error saying 'TextEncoder is not defined' when running Jest in Next.js version 14

I am currently working on testing some API call methods using Jest in a Next.js 14 environment. Below is my jest.config.js file: const nextJest = require("next/jest"); /** @type {import('jest').Config} */ const createJestConfig = next ...

Retrieve information according to the object ID with AngularJS UI-Router and $stateParams

I have a unique application that directs to a custom URL based on a specific employee ID parameter when an individual employee is clicked in a list. Upon clicking the employee, users are redirected to a detailed employee page with their ID property as a pa ...

Utilizing Jquery to Pass an Optional Function to Another Function

I am currently working on a function that utilizes AJAX to submit data and then displays a dialog indicating whether the process was successful or not. Everything seems to be functioning smoothly, but I now want to add the capability of passing an addition ...

I'm facing an issue where the data I retrieved is not displaying properly in my template within nuxt 3

After fetching data from an api, I can see it logged in my async function. However, the data stored in my array is not rendering on my template in Nuxt 3 The script setup includes: //ARRAY OF ALL THE DAILY WEATHER DATA PER DAY let allDataWeather=[]; ( ...

Creating an event listener with a dynamic name

I'm in the process of developing a customizable button bar where I need to attach onclick event listeners to each button dynamically. The functions to be assigned should have names provided by the button's data-function attribute. … <div cl ...

Utilizing getIdentifier() and getStringArray() to reference a string array in Android using a different string

I am dealing with various string arrays that I need to access based on the user's selection. I am hesitant to use a SQLite DB because I am still new to Android/Java and have been struggling to find relevant examples. I understand that this may not be ...

Top method for triggering an action on the client-side during Sign In with the help of Redux, React, and NextAuth

Currently, I am developing a web application that utilizes the Spotify API. My goal is to seamlessly load the user's playlists as soon as they log in using NextAuth. At the moment, there is a button implemented to trigger playlist loading, but it onl ...

Discover a portion of the worth stored in the dictionary

Here is the dictionary I am working with: ["uno" : "unoValue", "dos" : "dosValue", "tres" : "tresValue"] I am trying to extract keys that contain specific characters. For example, if I search for 'no', I should only get the key "uno" because of ...

"Integrating Laravel 5.4 Backend with Angular 5 Frontend: A Step-by-Step

Currently, I am immersed in a project that involves creating a frontend using Angular 5 and backend business logic using Laravel 5.4 with MySQL Database. As someone new to this technology stack, I find myself grappling with establishing the data flow conne ...

Combining array elements with unique property labels

I have two arrays of objects containing the properties: name, value, and id Array A ArrayA: [{ name: , value: , key: }, ]; There is another array of objects, but with different property names ArrayB: [{ user: “userA” , email: ...

React - a search feature for array filtering

Lately, I've been delving into the intricacies of implementing a live search input that interacts with an array to create a file tree. Here is where you can find all the code: https://codesandbox.io/s/815p3k3vkj Although the solution seemed straightf ...

Setting up initial values for React properties

Below is the React code snippet I am currently working with: this.state = { colsHiddenStatus: new Map([['rowNumber',true], ['id', false], ['firstName', false], ['lastName', false], ['mobile', false], [&a ...

Using target="_blank" does not seem to open a popup window in React

The issue is that the target="_blank" attribute is not working properly for the modal popup window. Instead, the link is opening in the same page and the popup is closing. <TermLink to="/legal/privacy-policy" target="_blank"> Privacy Pol ...

Determine whether the current time falls within the specified time slots and check if the day is included in the provided array of days

Listing my Weekly Schedule: weekly_schedule: any[] = [ { id: 0, value: 'Monday' }, { id: 1, value: 'Tuesday' }, { id: 2, value: 'Wednesday' }, { id: 3, value: ...

The process of allocating memory for a 3D array and utilizing the fread function in C yields significant outcomes

// Initial Code int dim1=height; int dim2=width; int dim3=3; int k; unsigned char *** image = (unsigned char ***)malloc(dim1*dim2*3); for (i = 0; i < dim1; i++) { image[i] = (unsigned char **)malloc(dim2*sizeof(uns ...

Unable to access the value property of null in Angular reactive form when attempting to retrieve the value

{ "estimate_number": "2020-1234", "brand": "PF", "floor": "Laminaat", "floor_type": "Normaal", "plint_type": "Hoog", "floor_installer": { "id": "14", "name": "Maestro" }, "address": { "street": "Straatnaam 19", "city": "Amst ...

How can I locate an element using JavaScript in Selenium with C#?

Dealing with an outdated portal that requires the use of IE. There are certain elements, such as those within a <td> menu, that cannot be located. I attempted to locate them using XPath, but it was unsuccessful. Upon further inspection, I discovered ...