Loop through a multi-dimensional array in JavaScript, apply a filter, and generate a fresh array

After coming across a post on Stack Overflow, I realized it wasn't exactly what I needed. My JSON file is quite large and has the following structure:

{
    foo: [1, 2, 3, ...],
    bar: [
        {
            name: 'abc',
            cl: 2,
            data: [
                      [[2, 4, 6], [4, 5, 6]],
                      [[5, 3, 5], [5, 7, 9]],
                      [[6, 8, 9], [6, 8, 9]],
                      ...
                  ]
        },
        {
            name: 'def',
            cl: 1,
            data: [10, 20, 30, ...]
        }
    ]
}

I have a class that represents this object and can extract its properties and sub-objects. The foo property is required while the presence of the bar property is optional. The data property can be an array of varying dimensions. The lengths of both foo and data are always the same. Now, I want to reduce the content size of the file while preserving its structure by creating a new object with a shorter length or range based on specified criteria. For example, if I specify from foo[0] to foo[1], then the data property should also follow suit from data[0] to data[1] in the new object.

Is this achievable? If so, how can I go about it? Perhaps utilizing the map method? But how?

function filter(obj, from, to){
     /// ?
}

Thank you.

EDIT:

The resulting reduced object should resemble something like this:

{
    foo: [1, 2],
    bar: [
    {
        name: 'abc',
        cl: 2,
        data: [
                  [[2, 4, 6], [4, 5, 6]],
                  [[5, 3, 5], [5, 7, 9]]
              ]
    },
    {
        name: 'def',
        cl: 1,
        data: [10, 20]
    }
]
}

Answer №1

If you're looking to extract a specific portion of an array, you can leverage the Array#slice method. Here is an example implementation:

function slice(obj, from, to) {
    obj.foo = obj.foo.slice(from, to + 1);
    obj.bar.forEach(function (a) {
        a.data = a.data.slice(from, to + 1);
    });
}

var object = { foo: [1, 2, 3], bar: [{ name: 'abc', cl: 2, data: [[[2, 4, 6], [4, 5, 6]], [[5, 3, 5], [5, 7, 9]], [[6, 8, 9], [6, 8, 9]], ] }, { name: 'def', cl: 1, data: [10, 20, 30] }] };

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

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

In the world of node.js, functions almost always have a tendency to

As a beginner in the world of nodejs, I am diving into various guides and screencasts to grasp the basics. One aspect that has caught my attention is the handling of async/sync operations, reading files, and understanding how nodejs deals with callbacks/re ...

Ensuring the safety of PHP JSON output results on a web server

I am currently developing an app using phonegap that submits and retrieves data from a MySQL database hosted on a server (website). I have successfully implemented the data submission and retrieval features in the app. The data is fetched through AJAX fro ...

Having trouble retrieving information from the server using ajax, javascript, jquery, and php

I am currently facing an issue with sending data retrieved from a jQuery call and attempting to save it to a server file using PHP. function getSVG(){ svghead = svghead + $('#test').html(); $.ajax({ type:"POST", da ...

Adding products to an owl-carousel in an HTML document using JavaScript

When I try to add my products to an owl-carousel using JavaScript, the display is not correct. My HTML code looks like this: <div class="container mt-5 mb-5" data-aos-anchor-placement="top-center"> <div class="owl-carouse ...

Switching between filters using AngularJS toggle buttons

Currently, we are in the process of converting a jQuery application into an Angular application using JavaScript. The existing jQuery app functions, but we aim to transform it into a full-fledged app utilizing the Angular framework. The main concept behin ...

Converting integers to strings is not possible, just as converting strings to two-dimensional integer arrays is not

I find myself once again trying to solve the puzzle of error messages that keep appearing. Currently, I am delving into working with arrays - both regular and multi-dimensional. However, I am encountering difficulties in two areas: a) populating the arra ...

Dividing text into two separate arrays in C++

I have a text file filled with various data. The lines follow a specific pattern: 6 spaces, then an integer, then a space, and finally a string. Additionally, the first line of the text file indicates the total number of lines in the file. My goal is to s ...

Selected Elements are Displayed While Others Remain Hidden in Array Printing

In my Intro to Computer Language class, we have to develop minimal programs based on prompts. I encountered an issue with a Pig Latin translation program that uses for loops and different methods. Although I completed a different program due to time constr ...

Locating the (highest) index of the maximum element within an array using C++

I'm working with an array of values and have a method to find the index of the largest element in the array. value = distance(arrayOfValues, max_element(arrayOfValues, arrayOfValues + N)); The issue I'm facing is when there are multiple instance ...

How can I define the boundaries for the scrolling of a static background image?

Is there a way to limit how far a fixed background image can scroll down a page? Essentially, is it possible to change the background attachment to static when the bottom of the background image is 10px away from the bottom edge of its div container? In t ...

Triggering a JQuery slider event on each individual slider handle within the range

Can events be triggered based on the movement of individual slider handles? I am curious because I need to dynamically update a datepicker depending on which handle is moved. However, I'm unsure if there is a way to: Specify an event for a specifi ...

Sending values from multiple input fields created in PHP using AJAX can be done by following these steps

https://i.sstatic.net/GKcRc.png Within this snippet, there is a portion of a form that consists of 4 different fields/divs like the one shown. I am struggling to figure out how to send the values of these input fields to PHP using AJAX. I apologize if ...

Is it beneficial to use both Bootstrap and ng-bootstrap together?

I have two modules in my angular website - "bootstrap" and "ng-bootstrap". Do I need both or just one? I am thinking of keeping only "ng-bootstrap" 4.0.0.0 and removing "bootstrap". Is this acceptable? What are the steps to remove "Bootstrap"? Can I simp ...

When using Next.js to load a client-side library, the component undergoes multiple re-renderings as the state of the parent component changes

On the client side, I am loading the emoji-mart library because it requires the window object. After loading the library, a component is returned. However, when the component is called, it is initially rendered twice and then multiple times as the parent ...

Using jQuery to toggle the visibility of divs depending on the selection of multiple checkboxes

I found this code snippet that I need help with. <div class="row"> <div class="col-xs-4"> <label class="checkbox-inline"><input type="checkbox" value="draft">Draft</label> </div> <div class="c ...

What is the best way to slice the string into segments and organize them within an array?

On my website, there is a text box where users can input a series of numbers in the following format: (118,38,137,15,156,14,157,36,152,49,142,57) I want to know how I can store these numbers in an array as shown below: [118 38 137 15 156 1 ...

Guide on implementing enums (or const) in VueJS

Seeking help on a seemingly simple task, I am trying to understand how to use "enums" in VueJS. In my file named LandingPage.js, I have the following code: const Form = { LOGIN: 0, SIGN_UP: 1, FORGOT_PASSWORD: 2, }; function main() { new Vue({ ...

The HTTPOnly cookie is not accessible within the getServerSideProps function in Next.js

Why isn't the jid cookie available in getServerSideProps using Next JS? Here's the scenario: https://i.stack.imgur.com/FLRGk.png The jid cookie is generated by an Expressjs API at https://api-dev.example.com. I'm attempting to retrieve thi ...

Ways to eliminate a specific array from another array using JavaScript

0: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_amount: 9500, toppings: 500, …} 1: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_amount: 9500, toppings: 500, …} 2: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_am ...

A guide on utilizing ng-repeat to iterate through array values in Views

Need help with using ng-repeat on array values within an ng-repeat in VIEWS? The second ng-repeat is not functioning properly. Here is the value of generalDocument.documents: ["14-10-2015.xls","15-10-2015.xls","16-10-2015.xls"] <div class="box-body ...