Removing numerous key/value pairs from an object in real-time

Suppose I have an array of objects and I want to exclude certain keys/values. Instead of using the traditional delete method to remove one key/value pair, is there a way to specify which pairs I want to keep and remove all others? For example, in this array of objects, I only wish to retain trackName, kind, and price:

var tracks = [{
    trackNumber: "01",
    trackName: "Track 1",
    trackDuration: "5:35",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "02",
    trackName: "Track 2",
    trackDuration: "5:15",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "03",
    trackName: "Track 3",
    trackDuration: "5:07",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "04",
    trackName: "Track 4",
    trackDuration: "0:16",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "05",
    trackName: "Track 5",
    trackDuration: "5:35",
    kind: "song",
    currency: "USD",
    price: 1.29
}];

Answer №1

Loop through the array and select specific properties from each object.

let properties = ['name', 'type', 'cost'];

for(let j = 0; j < itemsArray.length; j++){

    for(let prop in itemsArray[j]){
        if(properties.indexOf(prop) === -1) delete itemsArray[j][prop];
    }

}

Answer №2

My recommendation for a more refined solution would be:

// Transform the existing array of objects into a new array
var updatedTracks = jQuery.map(tracks, function(item, position){
    return {"trackName": item.trackName, "type": item.type, "cost": item.cost};
}); 
// Clear the original array   
tracks = null;

Answer №3

Would you be okay with utilizing the underscore method ".pick(object, *keys) " and ".omit(object, *keys) " to extract specific keys from an object and then adding the resulting objects into a new array?

Answer №4

An effective approach:

// specify the data you wish to retain:
var dataToRetain = ['trackName', 'kind', 'price'];

// iterate through each main element of tracks:
for (var index=0; index<tracks.length; index++)
    // loop through each property of the current track:
    for (var prop in tracks[index])
        // check if the current track property is in the list of desired data:
        if (dataToRetain.indexOf(prop) < 0)
            delete tracks[index][prop];

Answer №5

Here is a straightforward solution that I came up with:

/**
 * Create a new collection containing only specified properties
 * @param {Array} the original collection of items
 * @param {Array} properties to be retained
 */

function keepCollectionProperties(collection, properties) {
    return collection.map(function(item) {
        var newItem = {}
        for(var i = 0, prop; prop = properties[i]; i++)
            if (typeof item[prop] !== 'undefined')
                newItem[prop] = item[prop]
        return newItem
    })
}

var tracks = [{
    trackNumber: "01",
    trackName: "Track 1",
    trackDuration: "5:35",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "02",
    trackName: "Track 2",
    trackDuration: "5:15",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "03",
    trackName: "Track 3",
    trackDuration: "5:07",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "04",
    trackName: "Track 4",
    trackDuration: "0:16",
    kind: "song",
    currency: "USD",
    price: 1.29
}, {
    trackNumber: "05",
    trackName: "Track 5",
    trackDuration: "5:35",
    kind: "song",
    currency: "USD",
    price: 1.29
}];

var output = keepCollectionProperties(tracks, ['trackName', 'kind', 'price'])
document.write(JSON.stringify(output))

Important: avoid using delete as it alters the object's structure and can impact performance. Try setting unwanted properties to null like item.prop = null. This function creates a new collection, so it may not be necessary, but if you intend to repopulate the new collection again, setting unwanted props to null would be recommended.

Answer №6

Uncertain if this meets your requirements, but it will iterate through a list and return a new list containing only the specified keys. The keys are provided in an Array.

function ExtractKeys(keys, list){
    var outputArr = [];
    for (var i in list){
       var row = {};
       for (key in list[i]){
          row[key] = list[i][key];
       }
       outputArr.push(row);
    }
    return outputArr;
}

There are alternate ways to modify the original list as well, although I opted to create a new list based on my understanding of your intentions.

If modifying the original list is desired, you could consider:

var select = ["a","b"]
list.map(function(val,index, array)
   {
   var keys = Object.keys(val);
   for (var key in keys){
      if(-1 == select.indexOf(keys[key]])  delete val[keys[key]];
   }}.bind(this));

I believe this approach should achieve the desired outcome by filtering out keys not included in the 'select' array from the original list.

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

Altering the context of Javascript script execution

I needed to switch the JavaScript execution context from the parent window to the child window. I was able to successfully load my script objects and functions into the child window context, however, I encountered difficulty in making third party libraries ...

Can you explain the concept of embedding the Chrome V8 engine in Node.js?

As I dive into the world of MEAN, a question arises: When learning about node.js, it is mentioned that node.js is powered by the Chrome V8 engine. This leads me to wonder if node.js is only compatible with specific browsers. Can someone explain why node. ...

Searching for a value within an array of objects using JavaScript: The ultimate guide

Similar Question: Locate specific object by id within a JavaScript objects array What is the best way to determine if a value exists in a given JavaScript array? For instance: var arr = [ {id: 1, color: 'blue'}, {id: 2, colo ...

Error encountered in PyArray_SimpleNew due to unauthorized access

My C++ project, based on cmake and wrapped with swig to Python, involves a method that returns a std::vector<int64_t>. This vector is then copied to a numpy array using the %extend keyword in swig (refer to foo.i below). foo.i %{ #define SWIG_FILE_W ...

Struggling with implementing the group by feature in AngularJS?

Currently, I am trying to group a select-window by 2 different object arrays - subcategories and rootcategories. Each subcategory has a relation id that links to the rootcategory's id. My goal is to have the dropdown window group the subcategories bas ...

Serialize data in C++ using the JSON format

I'm currently working with C++ code and encountering some difficulties when it comes to json serialization. string userInput; string const& returnedInput; while(!std::cin.eof()) { getline(cin, userInput); JSONClass exampleJSON; //Utilizi ...

Designing an architecture for a Java, Android, and database application - what will the final app's appearance be

I am currently working on a website where users need to complete tasks using an Android device: Fill out a simple HTML document. Sign the document on their Android device. Save the data entered into a database on the website. Some key points to consider ...

Issues with cross-browser compatibility are arising in my jQuery code

Here is the code snippet I'm working with: function toggleLoader( display ){ if( display === 'show' ){ $('.overlay, .loader').css({ 'z-index' : '1000', 'display& ...

Activate DivMenu's second list item automatically

I've been trying to use the trigger function multiple times, but it just won't work. I need help with auto-triggering the menu of the second list element. Can someone please assist me? Here is a snippet of my code: $("document").ready(functio ...

Web server experiencing issues with loading scripts and CSS files

After successfully building my project using CodeIgniter on localhost, I encountered an issue when trying to run it on a webhost. The site was functional but the design elements such as scripts and stylesheets were not loading properly. Before uploading t ...

Avoid using "out" when invoking the PHP function to access the database

I am attempting to call a PHP function from JavaScript by passing three arguments. On the PHP side, the function within the PHP file retrieves two values from the database and prints all the values. However, the code I have written does not seem to be work ...

Navigate to the top of the page using jQuery

Attempting to implement a simple "scroll jump to target" functionality. I've managed to set it up for all parts except the "scroll to top". The jumping works based on the tag's id, so it navigates well everywhere else, but not to the very top. He ...

The sluggish upload speed on Vimeo when using a library versus uploading directly

I have successfully integrated a library for uploading videos from my web app to Vimeo. Everything is working smoothly, but I am facing an issue with the upload speed. After running some tests, I noticed that the upload speed using the library is significa ...

Is styling in React not showing up?

Currently, I am tackling a third-party pagination component in Reactjs. The npm package instructs me to include the line import "rc-pagination/assets/index.css"; in the file. However, despite injecting the index.css into the DOM using the style loader, I ...

Check if the array includes a specific index

Below is the code snippet I am currently working with: <li *ngFor="let item of serviceList; let i = index;"> <button *ngIf="currentTools contains i" (click)="processService(item)"> Run Service</button> </li> Is t ...

How can we track and record NaN values in JavaScript/TypeScript as they occur in real-time?

Is there a reliable method to identify and prevent NaN values during runtime, throughout all areas of the application where they might arise? A) Are there effective linting tools available to alert about possible occurrences of NaN values within specific ...

Tips for effectively injecting retrieved API response data into a Table

Creating a google-map with customized markers that are logos of companies is the goal. Obtaining a json file from the APIs containing the vessels of interest has been successful. The challenge faced is injecting these vessels into a table on the user inte ...

Caution: the index of the array is outside the boundaries of the array [-Warray-bounds] within the

static int myarray[2]={-1,234}; module_param_array(myarray,int,&arrayargc,0); MODULE_PARM_DESC(myarray,"Integer Array"); static int __init module_init_2(void) { int i; for(i=0;i< (sizeof myarray/sizeof(int));i++); { printk(KERN_INFO "mya ...

Tips for managing cookies in an Angular.js project

At the moment, I am utilizing an AngularJS application. To store certain values in a cookie, I incorporated the angular-cookies-min script to add values to cookies. The following code snippet was used to save values to a cookie: $cookieStore.put("userIn ...

What is the Dojo counterpart for jQuery's .live() function?

Is there a Dojo alternative to jQuery .live() function? http://api.jquery.com/live/ In my search, the only workaround I came across was to disconnect the event handlers in Dojo and then reconnect them when new dynamic content is added to the page. ...