Ways to remove identical key from distinct object within an array

Is there a way to remove specific date keys from multiple objects in an array of objects?

I attempted to use a for loop and the delete function, but it doesn't seem to be working.

 var data = matchScoreData.tbl_FallOfWicket;
 matchScoreData.tbl_FallOfWicket.forEach(element => {
    if (matchScoreData.tbl_FallOfWicket.hasOwnProperty("createdDate")) {
                  delete ["createdDate"];
    }
 });
 console.table(data);

 var matchScoreData = {
    "tbl_FallOfWicket": [
                {
                  "pk_fallWicketID": 119,
                  "fk_matchID": 133137,
                  "fk_teamID": 141065,
                  "fk_dismissTypeID": 3,
                  "fk_dismissPlayerID": 969155,
                  "run": 40,
                  "wicket": 1,
                  "over": "5.1",
                  "inning": 1,
                  "createdDate": "2018-08-18T03:06:12+0000",
                  "modifiedDate": "",
                },
                {
                  "pk_fallWicketID": 120,
                  "fk_matchID": 133137,
                  "fk_teamID": 141065,
                  "fk_dismissTypeID": 1,
                  "fk_dismissPlayerID": 939721,
                  "run": 88,
                  "wicket": 2,
                  "over": "9.5",
                  "createdDate": "2018-08-18T03:06:12+0000",
                  "modifiedDate": "",
                  "inning": 1
       }
    ]};

The output remains unchanged despite attempts to delete the date keys.

Answer №1

When working with the following code, make sure to reference the current element within your if condition rather than the original object. You can achieve this by using delete element["yourkey"].

Check out the JS code below for a solution:

var data = matchScoreData.tbl_FallOfWicket;
    matchScoreData.tbl_FallOfWicket.forEach(element => {
      if (element.hasOwnProperty("createdDate")) {
        delete element["createdDate"];
      }
    });
    console.table(data);

Answer №2

The issue you are facing is due to using delete["createdDate"] instead of delete element["createdDate"], which is necessary to delete the correct property from the iterated element.

matchScoreData.tbl_FallOfWicket.forEach(element => {
  if (element.hasOwnProperty("createdDate")) {
    delete element["createdDate"];
  }
});

Important:

Another critical problem in your code is

if (matchScoreData.tbl_FallOfWicket.hasOwnProperty("createdDate"))

matchScoreData.tbl_FallOfWicket is an array, so this condition will always return false. As a result, delete['...'] is never executed.

You need to check each individual object instead.

if (element.hasOwnProperty("createdDate"))

Example:

var matchScoreData = {
  "tbl_FallOfWicket": [{
      "pk_fallWicketID": 119,
      "fk_matchID": 133137,
      "fk_teamID": 141065,
      "fk_dismissTypeID": 3,
      "fk_dismissPlayerID": 969155,
      "run": 40,
      "wicket": 1,
      "over": "5.1",
      "inning": 1,
      "createdDate": "2018-08-18T03:06:12+0000",
      "modifiedDate": "",
    },
    {
      "pk_fallWicketID": 120,
      "fk_matchID": 133137,
      "fk_teamID": 141065,
      "fk_dismissTypeID": 1,
      "fk_dismissPlayerID": 939721,
      "run": 88,
      "wicket": 2,
      "over": "9.5",
      "createdDate": "2018-08-18T03:06:12+0000",
      "modifiedDate": "",
      "inning": 1
    }
  ]
};

var data = matchScoreData.tbl_FallOfWicket;
matchScoreData.tbl_FallOfWicket.forEach(element => {
  if (element.hasOwnProperty("createdDate")) {
    delete element["createdDate"];
  }
});
console.log(data);

Answer №3

To remove the createDate property, you can use this code: delete element.createDate

var matchScoreData = {

  "tbl_FallOfWicket": [{
      "pk_fallWicketID": 119,
      "fk_matchID": 133137,
      "fk_teamID": 141065,
      "fk_dismissTypeID": 3,
      "fk_dismissPlayerID": 969155,
      "run": 40,
      "wicket": 1,
      "over": "5.1",
      "inning": 1,
      "createdDate": "2018-08-18T03:06:12+0000",
      "modifiedDate": "",
    },
    {
      "pk_fallWicketID": 120,
      "fk_matchID": 133137,
      "fk_teamID": 141065,
      "fk_dismissTypeID": 1,
      "fk_dismissPlayerID": 939721,
      "run": 88,
      "wicket": 2,
      "over": "9.5",
      "createdDate": "2018-08-18T03:06:12+0000",
      "modifiedDate": "",
      "inning": 1
    }
  ]
};

var data = matchScoreData.tbl_FallOfWicket;
matchScoreData.tbl_FallOfWicket.forEach(element => {
  if (element.hasOwnProperty("createdDate")) {
    delete element.createdDate;
  }
});
console.log(data);

Answer №4

Success!

let scoringData = {
  tbl_FallOfWicket: [
    {
      pk_fallWicketID: 119,
      fk_matchID: 133137,
      fk_teamID: 141065,
      fk_dismissTypeID: 3,
      fk_dismissPlayerID: 969155,
      run: 40,
      wicket: 1,
      over: "5.1",
      inning: 1,
      createdDate: "2018-08-18T03:06:12+0000",
      modifiedDate: ""
    },
    {
      pk_fallWicketID: 120,
      fk_matchID: 133137,
      fk_teamID: 141065,
      fk_dismissTypeID: 1,
      fk_dismissPlayerID: 939721,
      run: 88,
      wicket: 2,
      over: "9.5",
      createdDate: "2018-08-18T03:06:12+0000",
      modifiedDate: "",
      inning: 1
    }
  ]
};

for(let i=0;i<scoringData.tbl_FallOfWicket.length;i++){
    delete scoringData.tbl_FallOfWicket[i].createdDate;
    delete scoringData.tbl_FallOfWicket[i].modifiedDate;
}

console.log(scoringData);

Answer №5

Utilizing the map function and destructuring when assigning output to a new variable can streamline your code.

var matchScoreData = {"tbl_FallOfWicket":[{"pk_fallWicketID":119,"fk_matchID":133137,"fk_teamID":141065,"fk_dismissTypeID":3,"fk_dismissPlayerID":969155,"run":40,"wicket":1,"over":"5.1","inning":1,"createdDate":"2018-08-18T03:06:12+0000","modifiedDate":""},{"pk_fallWicketID":120,"fk_matchID":133137,"fk_teamID":141065,"fk_dismissTypeID":1,"fk_dismissPlayerID":939721,"run":88,"wicket":2,"over":"9.5","createdDate":"2018-08-18T03:06:12+0000","modifiedDate":"","inning":1}]};

const data = matchScoreData.tbl_FallOfWicket.map(obj => {

  // Extract dates and assign the rest of the properties to "rest", then return those properties
  const { createdDate, modifiedDate, ...rest } = obj;
  return rest;
});

console.log(data);

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

Python is unable to retrieve JSON data from the JSON source

Currently, I'm facing a challenge in extracting data from Verizon's buyback pricing website. While exploring the "Net" requests in my browser, I stumbled upon the source of the data. The site presents information in JSON format, but despite numer ...

How to Send and Receive Data in One Request Using Android Studio and Web API

Currently, I am working on an Android App using Android Studio and the backend is being developed using Asp.Net Web API. Web Api Part [System.Web.Http.AcceptVerbs("GET", "POST")] [System.Web.Http.HttpGet] public dynamic GetTest(string name) { List< ...

Modify the key within an array of objects that share a common key

I have an object structured as follows: NewObjName: Object { OLDCOLUMNNAME1: "NEWCOLUMN_NAME1", OLDCOLUMNNAME2: "NEWCOLUMN_NAME2", OLDCOLUMNNAME3: "NEWCOLUMN_NAME3"} Next, there is an array containing objects in this format: ...

Problem encountered when trying to use a single button for both opening and closing functionality in JQuery

Hello everyone, I'm currently working on creating a button that toggles between opening and closing. When clicked the first time, it should open, and when clicked the second time, it should close and reset. Here is the code I've written so far. ...

Deconstruct singular JSON data using PHP

Currently, I am in the process of creating a backend using php and codeigniter. This backend connects to a data service that provides JSON data structured like the example below: { "code": "36397_26320", "type": "TEAMS", "4522": { "id": "4522", "c ...

Nodeca's js-yaml now allows appending '>-' to handle extended strings with ease

With the npm package js-yaml, I am attempting to work with a .yaml file. Although I can manipulate it successfully, I encounter an issue when trying to save a long string. Actual: abvs_adas: >- c2Rhc2Rhc2Rhc2Rhc2RwaW9qbGtkZ2hqbGtzZGhmZ2psaGFzamh ...

Language translation API specifically designed to convert text content excluding any HTML formatting

I have a dilemma with translating text content in an HTML file into multiple languages based on user input. To accomplish this, I am utilizing the Microsoft Translator AJAX interface. The structure of my HTML file looks something like this; <h1>< ...

Adjusting and arranging multiple thumbnail images within a container of specific width and height

I need a user-friendly method to achieve the following. The thumbnails will not be cropped, but their container will maintain a consistent height and width. The goal is for larger images to scale down responsively within the container, while smaller image ...

Utilizing HTML, CSS, and JavaScript to dynamically add and remove a class from

I've been struggling with a specific issue in my 9-button grid. When I click on a button and it changes color to orange, if I click on another button, both buttons remain orange. What I want is for only one button at a time to be orange - when a new b ...

Ways to recycle a section of Javascript for multiple uses on a single page

As a newcomer to website building, I have a query regarding the usage of a JavaScript function designed for a slideshow. My one-page website comprises multiple slideshow units with their own divs, holders, and counters (e.g., 1/4). A JavaScript code contro ...

Adjusting Iframe Dimensions Dynamically with Javascript based on Anchor Location

I am experienced with handling this issue in flash, but I am struggling to figure out how to do it using Javascript and CSS. The problem involves an iframe that does not have an overflow property, and I need to modify its width/height. Is there a simple ...

Tips for saving a text input from scanf into an array

#include<stdio.h> #include<string.h> #include<stdlib.h> int main(){ char *array[3]; scanf("%s",----); // Input is james. return 0; } Is there a way to input the string "james" and store it in array[1] so that it is equival ...

Using regex, match any word along with the preserved white space and consider parentheses as a single word

I need help with creating a regex pattern to split a string of words in a specific way. The current pattern I've been using is (?!\(.*)\s(?![^(]*?\)), but it's not giving me the desired outcome. It's close, but not quite the ...

Encountering the issue of "TypeError: Cannot read property 'file' of undefined" when trying to upload a video with Multer

The objective is to select a video file from the desktop and upload it to the platform. The uploaded video file will then be automatically posted to a specified Youtube channel using GCD. An error message I encountered is:"react-dom.development.js:40 ...

There was a failure to retrieve any data when trying to send an ajax request to

When attempting to send JSON data to my PHP, I am not receiving any response when accessing it in my PHP code. Below is the Ajax request being made: var project = {project:"A"}; var dataPost = JSON.stringify(project); $.ajax({ url: 'fetchDate.p ...

Send an encrypted POST request containing a JSON body to the R server

Currently, I'm working on utilizing R to send an encrypted request to an API. The specific request in question is the /v3/orders/ one. This request necessitates the utilization of an API key and secret, along with a progressively increasing nonce. ...

How should I proceed if a TypeScript definition file that I am relying on is lacking a specific definition?

I have encountered an issue while using the React type definitions for my project. The focus method is missing on elements in the array returned by the refs property, which prevents me from getting a specific example to work. The compiler error states: pro ...

Produce Struts 2 JSON Output while Executing Action

Struggling to implement caching of JSON responses in Struts 2 Action calls. Want to generate and cache the JSON response within the code before making the call. Considered including this snippet within an action's execute() method: String json = this ...

JavaScript - Identifying Repetitive Items in an Array

My goal is difficult to explain in words, but I can show you with code. Here is the array I am working with: var array = [{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"},{name:"John",lastname:"Doe"}] This array has duplicate elements, and I n ...

Preventing SQL Injection by properly formatting SQL queries

In my Node.js application, I need to construct an SQL query that looks like the one shown below. SELECT * FROM my_table WHERE my_column IN ['name1','name2'] The user inputs an array, such as ['name1', 'name2'], whic ...