Tips for eliminating an array from another array based on the key name

I am looking to modify my data slightly by removing certain keys (arrays within another array) if their name contains a specific phrase.

For instance, consider the following data:

var data = [{
    "toRemove_item1": [],
    "name": "Joe"
}, {
    "toRemove_item2": [],
    "name": "Adam"
}, {
    "name": "Peter",
    "toRemove_item3": []
}]

Now, I want to eliminate any keys in the array that have "toRemove_" in their name.

This would result in something like:

var data = [{
    "name": "Joe"
}, {
    "name": "Adam"
}, {
    "name": "Peter"
}]

Is this achievable?

Answer №1

To remove all toDelete_... properties, you can utilize the array.prototype.forEach method to loop through the array and check for any matching toDelete properties within each object.

If a match is found, the property is then deleted.

var data =  [
    {
        "toDelete_item1": [],
        "name": "Joe"
    },
    {
        "toDelete_item2": [],
        "name": "Adam"
    },
    {
        "name": "Peter",
        "toDelete_item3": []
    }
];

data.forEach(function(item,index){
    for(var prop in item) { 
        if (prop.match(/toDelete/) !== null) {
            delete item[prop];    
        }
    }
});

console.log(data);

This solution works specifically for the given scenario. To make it more versatile, let's convert it into a function that only deletes properties within objects contained in the data array, without recursion.

In this revised version, we use the match method instead of indexOf for increased flexibility. No need to check if the property exists; either there is a match or not.

var data =  [
    {"toDelete_item1": [], "name": "Joe"},
    {"toDelete_item2": [], "name": "Adam"},
    {"name": "Peter", "toDelete_item3": []},
    ["toDelete_item4", "Foo"],
    "toDelete_item5"
];

function delPropFromObjsInArr (reg, arr) {
    var regex = new RegExp(reg);
    arr.forEach(function(item, index){
        if (item === Object(item)) {
            for(var p in item) { 
                if (p.match(regex) !== null) {
                    delete item[p];    
                }
            }            
        }
    });    
}

delPropFromObjsInArr("toDelete", data);
console.log(data); 

Answer №2

It's a straightforward process of iteration and string checking.

To remove properties from objects, the delete keyword can be used.

When iterating through an object's properties, you can use for(propname in object). When dealing with an indexed array, propname will be an integer representing the current index.

If the object has named variables, it is important to check object.hasOwnProperty(propname) to avoid working on native objects or values.

var myArray =  [
        {
            "toDelete_item1": [],
            "name": "Joe"
        },
        {
            "toDelete_item2": [],
            "name": "Adam"
        },
        {
            "name": "Peter",
            "toDelete_item3": []
        }
    ]
 for(var i in myArray) {
   for(var key in myArray[i]) {
     if(myArray[i].hasOwnProperty(key)) {
       if(key.indexOf('toDelete_') === 0) {
         delete myArray[i][key]
         }
       }
     }
   }
console.log(myArray);

Answer №3

To efficiently filter out unnecessary elements from your array, you will need to use two nested loops. The outer loop iterates through each element in the array, while the inner loop goes through all the properties of each object within the array. If a property starts with 'toDelete_', it is removed from the object.

for (var index in myArray) {

    var item = myArray[index];

    for (var key in item) {
       if (key.indexOf('toDelete_') == 0) {
          delete item[key];
       }
    }

}

Answer №4

In Javascript, you can utilize the "delete" keyword to remove specific elements.

delete myArray["toDelete_item1"];

If you have multiple keys to delete, consider searching for them and storing in an array for sequential deletion.

For more information, check out this helpful resource: How do I remove objects from a javascript associative array?

Answer №5

Is this what you were looking for?

myArray.forEach( function(item){
    for(var x in item){
        if( item[x].constructor === Array){
            delete item[x];
        }
    }
});

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 methods are used to maintain the state of the express req.session object?

My journey into learning Node and Express is just beginning, and I am currently trying to comprehend the flow of code with Express. Imagine you have code like this in a session.js file: app.post('/session', notLoggedIn, function(req, res) { ...

Easy method to create an array of increasing numbers in Swift such as 1, 3, 5

How can you create an array with a progressive series like the following: 1,3,5,... up to 99 What changes should be made to this code to achieve that? let arrayAP = Array(stride(from: 1, through: 99, by: 2)) // 1,3,..99 ...

What causes adjacent elements in an int array to change when a number is appended in Golang?

I've been working on solving dynamic programming problems using Golang. One of the functions I wrote looks like this: func main() { fmt.Println(HowSum(5, []int{1, 2, 5})) } func HowSum(targetNum int, numbers []int) []int { retAry := make([][]in ...

Attempting to organize date and time down to the second

I'm currently working on sorting time with seconds included. While I am able to sort the minutes successfully, I'm facing difficulty in sorting the seconds. Despite trying various approaches and using dynamic data that needs to be sorted in desce ...

Can HTML/CSS be used to specifically target handheld mobile devices?

I am looking to optimize my video display in HTML by only showing it on desktop browsers. The difference in bandwidth between desktop and mobile devices is affecting the performance of mobile browsers, so I want to target only desktop users. Is there a way ...

Dynamic array filtering in MongoDB Compass

I need help filtering MongoDB based on the given JSON format to only return records with serviceCountry = US under gfcidGlobals. Other objects should be ignored. The desired output is the gfcidGlobals data and details associated with the serviceCountry. J ...

Retrieving data from a promise in Redux

Is there a way to access the data of the first dataElement in the array and log its name using console.log? import React, { Component } from 'react'; class Submit extends Component { componentDidMount() { const programStage = this.p ...

Leveraging 'fs' in conjunction with browserify

Exploring the functionality of fs in browserify Calling require('fs') results in an empty object being returned var fs = require('fs') ...

The jQuery request for the file was unsuccessful

Currently attempting to use jQuery.get('similar_products_stack.php'); as well as jQuery.get('./similar_products_stack.php'); My similar_products_stack.php file is designed to return an html array, however I keep receiving a 404 erro ...

"Developing a script to capture a user's screen using JavaScript and uploading it to a server through an

Launching my website's support option called for the inclusion of screenshots, which led me to discover the html2canvas library - a tool that exceeded my expectations. To start the process, I begin by preparing the user's screenshot: $( "#openH ...

What is the process for starting a game with a 'Start' button on the website?

Looking to create an engaging online game experience? Want to add a 'Launch' button on your game site to kickstart the client side game? Check out examples from popular online games, such as this one. How can you implement this feature seamlessly ...

Vue Nuxtjs enables seamless functioning across all pages without the need for explicit calls to the component

I need assistance with creating pages that are loaded via a component. Currently, the pages only call the home component. However, when I load all the pages (highlighted in the red box), the component is executed on each page. How can I ensure that the c ...

Encountering a 404 error while attempting to access my React project's login page

I'm facing a 404 error issue while trying to log into my web application, but I am struggling to identify the root cause. Check out the code snippets provided below for reference: view image description here Context: I have developed a web applicatio ...

What is the best way to divide an ArrayList and save it in a variable in C#?

I am struggling to split an array list by its delimiter "," and save it in a variable/string. The splitting process is proving to be unsuccessful for me. Here are the values: arr[0] = "1", "Illinois","Seattle" arr[1] = "2", "Michigan", "New York" arr[2] ...

Send backspace key press event to the applet and prevent it from continuing

I am struggling with a Java applet on my webpage that allows users to edit text. Whenever a user tries to modify the text by pressing the backspace button, the browser mistakenly forwards to the previous page. I attempted to filter out the backspace key pr ...

"Unlocking the Power of Promises: A Beginner's Guide to Utilizing JavaScript Prom

I recently started using Redux in my project and I encountered a scenario where I needed to make a network call after updating the store. To achieve this, I decided to use promises like so: let promise = new Promise(function(resolve, reject) { updateSt ...

Having difficulty rendering JSON data on an HTML webpage

Currently, I am working on an API App that utilizes the Foursquare API. With the help of my getRequest function, I am able to obtain results in JSON format, which are then displayed in my console.log. However, the challenge lies in parsing the data from J ...

Encountering a crash with the NativeDroid HTML5 JS css jQueryMobile template on iOS7

Recently, I began working on a mobile solution using the NativeDroid template, an HTML5 JS CSS template available at . However, a friend informed me that the template does not work on iOS7 devices. I tested it on multiple devices. Even when running the de ...

The behavior of comparing variables in Javascript

Encountering an unusual issue while attempting to compare two strings using regex. Even after comparing both variables in the watch, the result remains the same. Seeking assistance in identifying the cause. Below is my code and also an image showcasing the ...

Modify the text of a button in Angular to be underlined after it has

Is it possible to avoid DOM manipulation in the controller and keep it focused on business logic? I have a scenario with three buttons where I want to underline the text of the button when clicked. Here is a link to a demo: jsfiddle CSS: .underline { te ...