Convert data into JSON format and exclude any unnecessary keys

I am encountering some challenges while trying to create a new array from existing Objects. If I execute the following code snippet:

console.log(JSON.stringify(this.data))

The output is as follows:

{
    "nodes":[
        {"id":1,"node":"0","name":"pizza","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"},
        {"id":2,"node":"1","name":"pasta","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"},
        {"id":3,"node":"2","name":"pie","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"}
    ],
    "links":[
        {"id":1,"source":"0","target":"1","value":"451","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"},
        {"id":2,"source":"1","target":"3","value":"237","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"}
    ]
}

My objective is to extract only the 'node' and 'name' properties from the nodes array, and 'source', 'target', and 'value' properties from the links array. I have attempted various methods without success, such as:

const valuesToRemove = ['id', 'created_at', 'updated_at'];
this.data.links = this.data.links.filter((i) => (valuesToRemove.indexOf(i) === -1));

How can I achieve the desired result similar to the following structure?

{
    "nodes":[
        {"node":"0","name":"pizza"},
        {"node":"1","name":"pasta"},
        {"node":"2","name":"pie"}
    ],
    "links":[
        {"source":"0","target":"1","value":"451"},
        {"source":"1","target":"3","value":"237"}
    ]
}

Thank you.

Answer №1

If you want to filter array properties and retain only specific keys in an object, consider utilizing Array.prototype.map:

const data = {
    "nodes":[
        {"id":1,"node":"0","name":"pizza","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"},
        {"id":2,"node":"1","name":"pasta","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"},
        {"id":3,"node":"2","name":"pie","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"}
    ],
    "links":[
        {"id":1,"source":"0","target":"1","value":"451","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"},
        {"id":2,"source":"1","target":"3","value":"237","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"}
    ]
};
function transform(data){
    data.nodes = data.nodes.map(({node, name}) => ({node, name}));
    data.links = data.links.map(({source, target, value}) => ({source, target, value}));
    return data;
}
console.log(transform(data));

For a more flexible method, where instead of fixed property names, you pass them as an ES6 Set (for faster processing) and map the nodes accordingly:

const data = {
    "nodes":[
        {"id":1,"node":"0","name":"pizza","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"},
        {"id":2,"node":"1","name":"pasta","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"},
        {"id":3,"node":"2","name":"pie","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"}
    ],
    "links":[
        {"id":1,"source":"0","target":"1","value":"451","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"},
        {"id":2,"source":"1","target":"3","value":"237","created_at":"2019-09-01 09:56:01","updated_at":"2019-09-01 09:56:01"}
    ]
};

function transformDynamic(data, nodesToKeep, linksToKeep){
    data.nodes = data.nodes.map((ele) => {
       return Object.keys(ele).reduce((acc,key) => {
           if(nodesToKeep.has(key)){
              acc[key] = ele[key];           
           }
           return acc;
        }, {}); 
      })
    data.links =data.links.map((ele) => {
       return Object.keys(ele).reduce((acc,key) => {
           if(linksToKeep.has(key)){
              acc[key] = ele[key];           
           }
           return acc;
        }, {}); 
      });
    return data;
}
const nodesToKeep =  new Set(["node", "name"]);
const linksToKeep =  new Set(["ource", "target", "value"]);
console.log(transformDynamic(data, nodesToKeep, linksToKeep));

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

Navigating through an array object

I am currently utilizing react-select and aiming to iterate through an object in order to display it as the select element's value and label: // Within the render method of the component: var myVar = [ this.props.foo.forEach(function(a){ {valu ...

What is the significance of property placement in a Mongo query: at the beginning versus at the

Currently, I am in the process of creating a query to retrieve data from the mango collection. Interestingly, I have written the same query in two different ways. Here is my working query: db.getCollection('routes').find({"routes.routeId": "r1q ...

Transmit the value of radio button data to PHP using Ajax

I'm facing an issue in sending radio button data to PHP using JavaScript. For example, when the radio button "Mother" is selected, the value "Mother" should be sent via AJAX. However, I'm struggling to achieve this functionality and haven't ...

Discovering if the array data is already present in Angular can be accomplished by using specific methods

Here is the snippet of code: data = [ { 'id': 'asdjxv', 'username': 'emma', }, { 'id': 'asqweja', 'username': 'adam', }, { ...

How to show or hide a textbox in JavaScript?

Within my user control, there is a panel with two controls: ddlType, a drop-down list, and txtOthers, a text box. Initially, txtOthers is set to be invisible. The goal is for txtOthers to become visible when the user selects an option in ddlType that corr ...

Tips to successfully save and retrieve a state from storage

I've encountered a challenge while working on my Angular 14 and Ionic 6 app. I want to implement a "Welcome" screen that only appears the first time a user opens the app, and never again after that. I'm struggling to figure out how to save the s ...

Troubleshooting why the second statement is not being triggered by the Vuejs

Incorporating a lambda expression into the methods section of a Vuejs component has been a recent challenge for me. Here's an example: I initiate alertyou() and upon receiving the alert, I click okay. Subsequently, in the Vue developer tools, I notic ...

Cross-Origin Resource Sharing using Express.js and Angular2

Currently, I am attempting to download a PLY file from my Express.js server to my Angular/Ionic application which is currently hosted on Amazon AWS. Here is the Typescript code snippet from my Ionic app: //this.currentPlyFile contains the entire URL docum ...

Attempting to grasp the concept of Thennables within the VSCode API. Can these TypeScript code examples be considered equivalent?

I'm looking to perform a series of modifications on a document using the VSCode API. The key function in this process is Workspace.applyEdit, which gives back a Thennable. This is my first encounter with it, and the one returned from this function doe ...

JavaScript issue: TypeError - Information.map is not a function. Learn how to properly use .map method

Currently, I am learning how to use CRUD in React with Express and Node. I have successfully inserted data into the database, but I encountered an error when trying to represent the data using .map. You can see the issue with <Input onClick="{getCR ...

What is the best method to identify false values within the properties of a series of interconnected objects?

I am currently utilizing the Logical OR (||) operator to verify and assign values if they are not falsy in the following manner: let locationDistrict = result.results[0].address_components[2].long_name || result.resu ...

The implicit wait feature in WebDriver JavaScript seems to be ineffective

Waiting for the error message to appear seems to be a bit tricky. I tried using browser.driver.manage().timeouts().implicitlyWait() but had to resort to using browser.driver.sleep() instead. this.getErrorMessage = function () { var defer = protracto ...

Error in Array arithmetic operation: unsupported operand type for subtraction - 'str' and 'str'

I am currently working with a dataset stored in an Array. The structure of the data is illustrated below: P=array([['984.6'], ['983.9'], ['983.2'], ..., ['7.8'], ['7.8'], ...

Executing a quick shallow copy of an object in a single ReactJS operation

I have an object in a component that I need to copy to a property. Currently, I am achieving this as follows: onSubmit: values => { data.label = values.label; data.userName = values.userName; data.recipientUserName = values.recipient ...

Endless loop of jquery textbox focus event

Currently, I am employing jQuery for validating textbox values. I have two textboxes - txt1 and txt2. For this purpose, I have created a jQuery function: $("#txt1").blur(function () { if ($("#txt1").val() == "") { $("#scarrie ...

Examining the potential of a promise within a dynamic import feature in Angular

Here's a code snippet that I'm working with: The component file (component.ts) looks like this: async ngOnInit() { import('dom-to-image').then(module => { const domToImage = module.default; const node = document.getEl ...

How can I retrieve the height of a dynamically generated div in Angular and pass it to a sibling component?

My setup consists of a single parent component and 2 child components structured as follows: Parent-component.html <child-component-1 [id]="id"></child-component-1> <child-component-2></child-component-2> The child-compo ...

Creating a circular sun in Opengl and three.js: a step-by-step guide

Currently, I am working on enhancing an atmospheric shader based on the glsl-atmosphere library while using three.js. Initially, I applied these shaders to a sphere and achieved excellent results :) The original shaders lacked sun drawing elements, so I ...

Can you explain the meaning of EPS in the THREE.OrbitControl function?

The this.update method within the THREE.OrbitControl script contains a private variable called EPS, which is used to adjust the phi angle. The following code snippet demonstrates how it restricts phi to be between EPS and PI-EPS: // restrict phi to be bet ...

Adding the AJAX response to the specified element's ID

I'm having trouble inserting radio buttons into a <div> on my page using an AJAX response. The code I have looks like this: // AJAX form for updating tests after category selection $('#categories').change(function(){ category_id ...