Creating a new array from an existing array in JavaScript

I am attempting to clean up this particular array of data:


 [
    {
      "Cpf": null,
      "Nascimento": null,
      "Sexo": null,
      "OnlyPerson": false,
      "IsFinanc": false,
      "Senha": null,
      "ConfirmaSenha": null,
      "Remover": false,
      "TipoStr": null,
      "FiltroStr": null,
      "IdAgenciaLogarComo": 0,
      "DontHashPass": false,
      "IsPessoaSimples": false,
      "IsVisitante": false,
      "Permited": false,
      "Id": 21980,
      "Nome": "arrozfeijao",
      "Ativo": true,
      "Criacao": "2021-08-19T14:09:06.173",
      "UltimaAlteracao": null,
      "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a3b282835203c3f33303b351a3d373b333674393537">[email protected]</a>",
      "IdAgencia": 1,
      "IdEndereco": null,
      "IdPermissao": 4,
      "Observacoes": null,
      "Endereco": {
        "Id": 0,
        "Cep": null,
        "Logradouro": null,
        "Numero": null,
        "Complemento": null,
        "Bairro": null,
        "Estado": null,
        "Cidade": null
      },
      "Parceiro": null,
      "Contato": [],
      "Permissao": {
        "Id": 4,
        "Descricao": "Cliente",
        "Pessoa": []
      },
      "AlterarSenha": [],
      "Rede": [],
      "Provider": [],
      "AlertaPreco": [],
      "Pedido2": [],
      "_PageNumber": 0,
      "PageNumber": 0,
      "PageSize": 0,
      "OrderBy": null,
      "OrderDesc": false
    }
  ]

These are the details for a checkbox selected in a table -> view image description here I require a function that can clean the array every time I select an additional checkbox. I have attempted to use the push method to store all necessary information in a new variable, but it fails when selecting checkboxes with different information...

I need to export these details to CSV file, but I only require the following fields:

  • "Cpf"
  • "Nascimento"
  • "Sexo"
  • "Id"
  • "Nome"
  • "Ativo"
  • "Criacao"
  • "UltimaAlteracao"
  • "Email"
  • "Observacoes"
  • "Endereco".

I understand that I need to use a for loop, but I'm unsure how to create this function :c

Answer №1

It seems like your data pertains to a single individual among multiple individuals, and here is a potential solution:

Initialize your arrays:

data: function () {
  return {
    oldArray: [],
    includesArray: ["Cpf", "Nascimento", "Sexo", "Id", "Nome", "Ativo", "Criacao", "UltimaAlteracao", "Email", "Observacoes", "Endereco"],
    newArray: []
  }
}

oldArray holds the original data, includesArray specifies the keys to be transferred to the new array, and newArray will store this updated data.

Add the following to your component:

created() {
    for (const [key] of Object.entries(this.oldArray)) {
      let tempObject = {};
      for (const [keys, values] of Object.entries(this.oldArray[key])) {
        if (this.includesArray.includes(keys)) {
          tempObject[keys] = values;
        }
      }
      this.newArray[key] = tempObject;
    }
  }

Answer №2

If you want to extract specific properties from an object, the Lodash pick method is a useful tool. One way to achieve this is by utilizing the following pseudo-code:

let updatedArray = initialArray.map(element => {
return _.pick(element, ['id', 'name']);
});

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

express.js creating dynamic URLs causing confusion

router.get('/:username', function(req, res, next) { res.render('dashboard'); }); router.get('/', function(req, res, next) { if(req.user) // this has value res.redirect('/'+req.user); }); I'm experi ...

Do specific href values need to be specified for document.links to return links?

Is there a shortcut to create an array of links in JavaScript without using a loop? var links = document.links; Instead of looping through the array to find elements with href attribute equal to '/somehref', is there a way to directly filter th ...

What is the best way to obtain a unique dynamic id?

This is the unique identifier retrieved from the database. <input type="hidden" name="getID" value="<?php echo $row['ID']; ?>"> <input type="submit" name="getbtn" value="Get ID"> How can I fetch and display the specific dynami ...

Implementing React component that clears state upon selecting a place with Google Autocomplete

I've encountered a issue while using the Google Autocomplete component. Whenever I select a place and use the onPlaceSelected function to save it into a state array (input) of the parent component, the previous value gets replaced with an empty array ...

Can you explain the significance of the file:workspaces in the package dependencies?

Attempting to utilize npm 7 workspaces feature "workspaces": { "packages": [ "packages/apps/*", "packages/components", ], Upon installation, my package.json includes: "dependencies": ...

Is there a way to retrieve php session in a javascript file?

Here's the code snippet for reference: Contents of index.php file Javascript code from index.php function Result() { var marks = 55; document.getElementById("hdnmarks").innerHTML= marks; window.location = "results.php"; } HTML code from ind ...

Changing variables from a different file in node.js: a guide

Currently utilizing the discord.js library for my project. Although I can refer to it as such, I am encountering issues when trying to access certain files. For example, let's consider a file named calc.js. In this scenario, I aim to retrieve a var ...

The input field for Google Places Autocomplete now includes the code "display: none"

I'm currently working on an AngularJS application and have implemented this directive to enable Google Maps API places autocomplete in the input field below. <div> <input type="text" autocomplete="off" g-places-autocomplete ...

How can we generate a compact sub-array from a larger 2D NumPy array using Python?

My NumPy array is quite large and is structured as follows: data = [[2456447.64798471, 4, 15.717, 0.007, 5, 17.308, 0.019, 6, 13.965, 0.006], [2456447.6482855, 4, 15.768, 0.018, 5, 17.347, 0.024, 6, 14.001, 0.023], [2456447.648575, 4, 15.8 ...

How can constants from components be defined in multiple ways when imported? (specifically in React)

Although I have a good understanding of React and Javascript, I struggle to articulate my question effectively. I will provide examples in the hopes that someone with more expertise in the field can assist me. For instance, when using import { useRef, use ...

Having trouble getting the JavaScript function to run when clicking a button inside a div or form?

Hey there, so I've got this scenario where I have a button nestled within a div. Take a look at the HTML snippet below: <div class="row"> <button type="button" id="submit">Send</button> </div> Prior to this button, there ...

Refresh the table following the removal of an item

I am currently working on displaying server data in a table. The delete function is functioning properly, but the deleted item only disappears from the table after refreshing the page. Is there a way to trigger a re-render of the component after deleting a ...

Checkbox malfunctioning when trying to add values after being checked

I have successfully completed a calculation system project using JavaScript. Everything works well, the calculations are accurate and taxes are included properly. However, I am facing an issue where the tax is not being included when I click on the checkbo ...

Cannot trigger a click event on nginclude in AngularJS

I have a question regarding including a new page using the nginclude directive. The click event defined in the included page is not working properly. Main Application: <div ng-app=""> <input type="text" ng-model="ss"/> <div ...

Generate selection choices by looping through a JSON document

I am attempting to develop a search box that will provide autocomplete suggestions based on user input from a key-value pair in a json file. I initially thought using datalist would be the most suitable approach for this task, however, upon running the cod ...

Is there a way to order the execution of two functions that each produce promises?

With my code, I first check the status of word.statusId to see if it's dirty. If it is, I update the word and then proceed to update wordForms. If it's clean, I simply update wordForms. I'm looking for advice on whether this is the correct a ...

Executing a jQuery.ajax call using a proxy server

I'm currently working on a Chrome extension and I have encountered an issue. When making a jQuery.ajax request for a standard HTTP page from a page served via HTTPS, Chrome blocks the request. This has led me to consider if it would be feasible to ret ...

Display images next to each other with no need for a scroll bar

I'm currently developing a Roulette website and I am struggling to make the roulette animation function properly. I have an image for the roulette wheel, but I need the image to vanish after reaching a certain point and then loop around to the left. ...

Adjust the point color of landmarks in Face-api.js

I need to customize the pointColor and lineColor in my code, but I'm not sure how to do it. I am using the fast-api.js library and haven't come across any examples of customized Landmarks Styles. export const drawResults = async (image, canvas, r ...

How can two unique links toggle the visibility of divs with two specific IDs?

I am developing an interactive questionnaire that functions like a 'create your own adventure' story. The questions are shown or hidden depending on the user's responses. Below is the HTML code: <!-- TIER 3 ============================== ...