JavaScript filter method returns a new array with all elements that

I have an Array of Objects with nested Arrays and Objects. Here's an example:

data = [{
    "id": 10022,
    "date": "2017-12-31T03:44:19.963808Z",
    "bought_beats": [{
        "id": 10034,
        "beat": {
            "id": 6334,
            "name": "Glass",
            "producer": {
                "id": 23,
                "display_name": "MadReal",
            }
        },
        "license": {
            "id": 10034,
            "name": "Premium",
        },
    }, {
        "id": 894,
        "beat": {
            "id": 6334,
            "name": "Other Name",
            "producer": {
                "id": 25,
                "display_name": "Other Name",
            }
        },
        "license": {
            "id": 10034,
            "name": "Premium",
        },
    }]
}, {
    "moredata": "stuff"
}]

I want to filter the bought_beats property and only return objects where beat.producer.id === 23

My current attempt is not working as expected:

data.forEach(order => {
    return order.bought_beats.filter(item => item.beat.id === producerId)
})    

===========

Edit1:

Although this solution "works", it also removes some properties (id & date) from each order object in the data array, leaving only the array of "bought_beats"

var res = data.map(item => item.bought_beats.filter(item => item.beat.producer.id === 23))

========

Edit2

After some trial and error, I found a solution that preserves the structure of the array and objects while removing the unwanted elements from the bought_beats array.

data.forEach(order => {
    let elementToRemoveIndex = order.bought_beats.findIndex(item => item.beat.producer.id !== 23)
    order.bought_beats.splice(elementToRemoveIndex, 1)
})

Many thanks to @Pac0 for the ongoing assistance

Answer №1

Opt for using the .find method instead of accessing data.bought_beats directly since it is an array,

DEMO

var data = [{
    "id": 10022,
    "date": "2017-12-31T03:44:19.963808Z",
    "bought_beats": [{
        "id": 10034,
        "beat": {
            "id": 6334,
            "name": "Glass",
            "producer": {
                "id": 23,
                "display_name": "MadReal",
            }
        },
        "license": {
            "id": 10034,
            "name": "Premium",
        },
    }, {
        "id": 894,
        "beat": {
            "id": 6334,
            "name": "Other Name",
            "producer": {
                "id": 25,
                "display_name": "Other Name",
            }
        },
        "license": {
            "id": 10034,
            "name": "Premium",
        },
    }]
}, {
    "moredata": "stuff"
}];

var result = data.find(dat => dat.bought_beats.some(item => item.beat.producer.id === 23));
    
 console.log(result);

Answer №2

If my understanding is correct, the following code snippet should meet your requirements:

// Filter and map the data to extract relevant beats
var beatsArrays = data.filter(x => x.bought_beats).map(x => x.bought_beats); 
var beats = [].concat.apply([],beatsArrays).map(x => x.beat); 
var relevantBeats = beats.filter(item => item.producer.id === 23); 

// Display the filtered result
console.log(relevantBeats);

Snippet :

   
data = [{ 
    "id": 10022,
    "date": "2017-12-31T03:44:19.963808Z",
    "bought_beats": [{
        "id": 10034,
        "beat": {
            "id": 6334,
            "name": "Glass",
            "producer": {
                "id": 23,
                "display_name": "MadReal",
            }
        },
        "license": {
            "id": 10034,
            "name": "Premium",
        },
    }, {
        "id": 894,
        "beat": {
            "id": 6334,
            "name": "Other Name",
            "producer": {
                "id": 25,
                "display_name": "Other Name",
            }
        },
        "license": {
            "id": 10034,
            "name": "Premium",
        },
    }]
}, {
    "moredata": "stuff"
}];

// Filter and map the data to extract relevant beats
var beatsArrays = data.filter(x => x.bought_beats).map(x => x.bought_beats); 
var beats = [].concat.apply([],beatsArrays).map(x => x.beat); 
var relevantBeats = beats.filter(item => item.producer.id === 23); 

// Display the filtered result
console.log(relevantBeats);

Answer №3

// looping through each order
data.forEach(order => {
    // iterating over the bought beats array
    order.bought_beats.forEach((item, index) => {
        // removing beats from other producers
        if (item.beat.producer.id !== producerId) order.bought_beats.splice(index, 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

Display intricate header and preview in a printed datatable

Hey there, I've been using the Datatable plugin and it's really great. However, I've come across a problem with complex headers like this: <thead> <tr><td>some text</td></tr> <tr><td>some te ...

Substitute the information in the table with new data

I am working with an HTML table that has 5 columns, one of which contains dates. I need to convert the date format only if the data is not empty. To achieve this, I am utilizing moment.js for date formatting. While the date format conversion works perfect ...

How can I designate unreleased files as dynamic entries in a webpack configuration?

Here is the configuration for webpack.config.js: const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); const fs = require('fs'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const path = require(&apo ...

Angular Script Linking

Hello there! I am currently attempting to add an HTML tag to my response message, but for some reason it isn't working as expected. Here is a snippet of my controller code (in case the API indicates that the account doesn't exist - see this scr ...

Determine the status of a script in PHP by incorporating AJAX

I am having trouble with my file upload page in the application. I want to display "Uploading" while the file is uploading and then show "Processing" while the file is being processed. Eventually, after the script completes, my page should redirect to a sp ...

The scaling of the slick carousel image is not working as expected

Having an issue with the Slick carousel where images are not resizing based on browser size (original size is 300x228px). Just to clarify: When I shrink the browser window, the number of slides decreases but the images remain the same size. I've bee ...

Is there a way to confirm that the content of two files is identical?

Currently, I am utilizing mocha/supertest/should.js for testing a REST Service. When I make a request to GET /files/<hash>, it returns the file as a stream. I am seeking guidance on how to use should.js to assert that the contents of the file are i ...

Discovering the value associated with a particular index in an array: A step-by-step guide

Looking to retrieve the value at a specific index in an array. The task is to extract the last digit in the array and utilize that digit as the index to search for in the array. For instance, if the array is 6543743, the goal is to return the value at the ...

Steps for deleting a row from a two-dimensional array

I am facing an issue that I am unable to resolve. I have created a 2-D array containing dates and prices. My goal is to delete any rows where the date falls between two specified dates. In the example provided, I am looking to delete the third row. Da ...

variable value remains constant after being updated

Here is the code snippet I am working with: function change(initial) { let a = initial; console.log(a); return [ a, (v) => { a = v; } ]; } const [val, setter] = change("initial"); console.log(val); setter("s&qu ...

develop the following application and execute the npm run dev command, but encounter the error message: "Command failed with exit code 1."

After executing npx create-next-app@latest followed by npm run dev, I encountered the error message Command failed with exit code 1.. Additionally, when trying to access https://localhost:3000, an error stating ERR_CONNECTION_REFUSED was displayed. Further ...

Include the session variable as an argument in the onload() function call

I've encountered a problem while trying to send the session variable $_SESSION["post-code"] as a parameter in the following code snippet... <body onload="getLocation('<?php echo $_SESSION['post-code'];?>')"> Within my ...

What is the correct way to use Deviceready in an Ionic application?

I am currently working on a mobile application built with Cordova and Ionic. The default page of the application requires the use of the SQLLite plugin. https://github.com/brodysoft/Cordova-SQLitePlugin The issue I am facing is that the view contains n ...

Node.js encounters issues when attempting to rename a folder

I am facing an issue while attempting to rename a folder within a WordPress theme after performing search-replace operations using a node script. The renaming process for the folder seems to be unsuccessful. My objective is to change this public_html/wp- ...

Setting the height to 100% on the body and html tags can lead to scrolling problems

After implementing the CSS code below, I have encountered some unexpected behavior: body, html{height:100%; overflow-x:hidden} Despite vertical scrollbars appearing as intended when the page exceeds screen height, detecting the scroll event on the body e ...

Navigating geometry with three.js - tips for making movements

Struggling with aligning cubes accurately using a script that positions cubes of different width, height, and depth on the xAxis, yAxis, and zAxis. var geometry = new THREE.BoxGeometry(width, height, depth); var cube = new THREE.Mesh(geometry, material); ...

React text hover image functionality

Just diving into the world of React and attempting to create a cool image popup effect when you hover over text in my project. I could really use some guidance on how to make it function within React, as the logic seems a bit different from plain HTML. Any ...

When the Materialparameters property transparent is set to true in threejs, the object becomes invisible

Currently, I am enrolled in Bruno Simons' class and in the session "Haunted House," he is teaching how to incorporate textures. So far, everything seems to be running smoothly and all the map textures are functioning perfectly. However, when I input t ...

Incorporating external CSS and JS files into your WordPress website

Hello, I am unfamiliar with the Wordpress framework and I am seeking guidance on how to add an external CSS and JS file to my Wordpress page. I have successfully created a new page, but would like to incorporate a CSS and JS file into it. Would creating a ...

Top approach for accessing data through a Factory function in Angular

Seeking guidance on the most effective method for fetching data from a local JSON file and managing the response. The plethora of options found on Stack Overflow has left me with conflicting thoughts, as different approaches yield similar results without c ...