gathering information from a group of items and organizing them into a fresh set of items

I have a collection of objects called Lines nestled within the rows array, which is nested within the tabs array. My goal is to extract specific data from the lines array and transfer them into a new array named 'colors'.

This is how the initial array appears:

"tabs": [{
  "selectedHouseType": "1",
  "rows": [{
    "selectedDecor": "2",
    "lines": [{
      "selectedColor": "white",
      "selectedQty": 0,
      "selectedUnit": "1"
    }, {
      "selectedColor": "black",
      "selectedQty": "2",
      "selectedUnit": "3"
    }]
  }, {
    "selectedDecor": "1",
    "lines": [{
      "selectedColor": "black",
      "selectedQty": 0,
      "selectedUnit": "2"
    }]
  }]
}, {
  "selectedHouseType": "select",
  "rows": [{
    "selectedDecor": "2",
    "lines": [{
      "selectedColor": "red",
      "selectedQty": 0,
      "selectedUnit": ""
    }]
  }]
}]

The objective is to extract data from the 'lines' array and populate a new array named 'colors', structured like this:

colors:  [{
          "selectedColor": "white",
          "selectedQty": 0,
          "selectedUnit": "1"
        }, {
          "selectedColor": "black",
          "selectedQty": "2",
          "selectedUnit": "3"
        },
        {
          "selectedColor": "black",
          "selectedQty": 0,
          "selectedUnit": "2"
        },
        {
          "selectedColor": "red",
          "selectedQty": 0,
          "selectedUnit": ""
        }
]

I am utilizing vue js for this task. Could you provide guidance on how to accomplish this?

Answer №1

To achieve a similar result, you can leverage the power of flatMap.

const info = {
  "panels":[
    {
      "selectedItemType":"1",
      "details":[
        {
          "selectedMaterial":"2",
          "items":[
            {
              "selectedColor":"blue",
              "selectedQuantity":0,
              "selectedSize":"small"
            },
            {
              "selectedColor":"green",
              "selectedQuantity":"3",
              "selectedSize":"medium"
            }
          ]
        }
      ]
    },
    {
      "selectedItemType":"choose",
      "details":[
        {
          "selectedMaterial":"2",
          "items":[
            {
              "selectedColor":"purple",
              "selectedQuantity":0,
              "selectedSize":"large"
            }
          ]
        }
      ]
    }
  ]
}

const itemColors = info.panels.flatMap(p => p.details.flatMap(d => d.items))

console.log(itemColors)

Answer №2

Give this a shot:

let combinedLines = tabs.reduce((acc, tab) => {
    let rows = tab.rows;
    let lines = rows.reduce((acc, row) => {
        let lines = row.lines;
        return [...acc, ...lines];
    }, []);
    return [...acc, ...lines];
}, []);

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

Tips for implementing a nested ng-repeat with nested JSON array data triggered by a button click

Assuming I have assigned the following JSON data to $scope.people: [ { "personId": 1, "name": "Thomas", "age": 39, "friends": [ { "friendId": 1, "nickName": "Lefty" ...

Can you explain the distinction between the onclick(function(){}) and on('click',function(){}) functions in jQuery?

My goal is to dynamically load pages into a specific div using ajax. Here's my HTML code: <ul id="nav" class="nav" style="font-size:12px;"> <li><a href="#" id="m_blink">Tab1</a></li> <li><a href="#" id= ...

Modify the styling of the input file in HTML to bind it with a

My file input setup looks like this; <input type="file" id="restoreFile"> To customize the appearance, I first set display: none; and created a label for the "restoreFile" input styled as a button. When I click the label (button) ...

Using more than one class at a time is causing issues

Essentially, I have a div and I want to create an exercise where I apply three different classes using vue.js. I attempted to use v-bind:class, specifically :class, but can I bind a class directly from CSS? This is what I tried: html <div :style="[my ...

Utilizing JavaScript to assign a CSS class to an <li> list item

I am working on a page that includes a menu feature: https://jsfiddle.net/dva4zo8t/ When a menu button is clicked, the color changes and I need to retain this color even after the page is reloaded: $('[id*="button"]').click(function() { $( ...

A guide on sending a post request with Axios to a parameterized route in Express

Recently, I set up an express route router.post('/:make&:model&:year', function (req, res) {   const newCar = {     make: req.params.make,     model: req.params.model,     year: req.params.year   }   Car.create(newCar);   res ...

The Node/Express Rest API appears to keep directing requests to the same controller function, despite the mappings being correctly

Currently, I am in the process of developing a node/express REST API. When making requests to the following endpoints: http://localhost:5000/api/news and http://localhost:5000/api/news/?id=c5f69d56be40e3b56e55d80 I noticed that both URLs trigger the same ...

Navigating through an array in Pug

I'm currently extracting data from an external API in JSON format and sending it to my view. The main issue I'm facing is that one of the properties within the Object consists of an Array of Objects. Using the Pug Documentation for iteration, I&a ...

Vue SPA authentication

After following various guides on implementing authentication in my Vue application with a .NET Core API backend, I have some questions. You can check out this guide: https://medium.com/dev-bits/a-guide-for-adding-jwt-token-based-authentication-to-your-si ...

Send data in JSON format along with an identifier using Jquery AJAX

I am having trouble sending JSON data along with 2 IDs using a jQuery AJAX post. Despite my efforts, I can't seem to get it working. Here is the code snippet in question: try { var surveyID = localStorage.getItem("surveyId"); var userDetails ...

When submitting an Asp net mvc Form, some fields may not be posted as expected

I'm facing an issue with my ASP.NET MVC application form. Some fields that should be posted are missing, and I can't figure out why. <form id="FormRegistroUsuario" action="/Account/AdminSecurityUserAccountAdd"> <fieldset> ...

A guide to efficiently passing props in a Vue.js application connected to Express with MongoDB

I am in the process of creating a simple chat application using Vue.js, Node, Express, and MongoDB. The app starts with a welcome page where users can input their names (refer to: Welcome.vue). After entering their name, users are directed to Posts.vue, pa ...

How to pass data from a child component to a parent component in React applications

In my search component, I need to pass a variable called "apiUrl" to the parent component. While I have successfully handled events for other parts of the code, I am unsure how to manage this specific variable transfer. The goal is to send the dynamically ...

After utilizing a while loop with class objects, make sure to reset them afterwards

I am facing a dilemma due to Js referencing objects. Within my Js "class," I have created a new player with various variables, strings, arrays, and functions to check specific conditions related to those variables. As part of my code, I am running a whil ...

Does using .detach() eliminate any events?

I have a DIV that is filled with various content, and I am using the detach() and after() functions to move it around within the document. Before moving the DIV, I attach click events to the checkboxes inside it using the bind() function. Everything seems ...

Determine the vertical distance that a div element is currently visible while scrolling

To better understand this concept, please refer to the following fiddle: http://jsfiddle.net/abhicodes/LasxP/ The main goal here is to calculate the visible height of the element with the ID #content-wrapper as the user scrolls. The height of the header ( ...

Making changes to the retrieved properties using Apollo GraphQL within a Vue.js environment

I'm trying to utilize the Moment javascript library to format a date that I retrieve through Apollo-GraphQL. My setup involves VueJS Apollo on the client side for executing graphQL queries like this: import { ALL_EVENTS } from '../constants/grap ...

Creating a fresh CSS class and utilizing its properties in JavaScript is the task at hand

Whenever I define a css class and attempt to access its member from JavaScript, the result always ends up being undefined. Where could my mistake possibly lie? function myFunction() { var x = document.getElementById("myId").style.myMember; document. ...

The dynamic nature of Vue.js when handling intricate data structures within a store

Complex Item Storage Issue I am facing a challenge with storing a list of complex items in a store and accessing them from a component. The data for these items is received through a mqtt interface and their values are updated in the store. However, the u ...

Choose a text input form field simultaneously?

Is it possible to create a select field that also acts as an input form simultaneously? I need the options in this hybrid field to range from 0.01 to 10.00, while ensuring it always displays 2 decimal places. Curious how I can achieve this functionality ...