What is the process for removing a key from an object and replacing it with its corresponding value?

My JSON sample looks like this:

var obj={
    "results":{
        "grade":"A",
        "marks":12
    },
    "data":{
        "name":"sam",
        "gender":"male",
        "age":10
    }
};

I am trying to transform the above JSON to:

var obj={
    "results":{
        "grade":"A",
        "marks":12
    },
    "name":"sam",
    "age":10
}

I attempted to achieve this using a forEach loop:

for(var exKey in obj) {
    if(exKey=='data'){
        //replace key data with its value
    }
}

Unfortunately, I couldn't figure out the logic needed to accomplish this. Can anyone provide assistance on how to achieve this? Thank you for your responses.

If dealing with more complex JSON like:

var obj={
"results":{
    "grade":"A",
     "res":"fail",
    "marks":12
},
"data":{details:{"name":"sam",
                 "gender":"male",
                  "age":10
                }
 },
 "feespaid":"yes",
 "joindate":"sunday"

};

In a scenario where I need to modify or delete keys within a nested structure, such as:

var obj={
"results":{
    "grade":"A",
    "marks":12
},
"data":{details:{"name":"sam",
                  "age":10
                }
 },
 "joindate":"sunday"
 };

How can we traverse through the JSON and perform deletions?

Answer №1

Utilize the inner for-in loop and employ bracket-notation to assign a variable as the key of an object

var obj = {
  "results": {
    "grade": "A",
    "marks": 12
  },
  "data": {
    "name": "sam",
    "gender": "male",
    "age": 10
  }
};
for (var exKey in obj) {
  if (exKey == 'data') {
    for (var d in obj.data) {
      if (d != 'gender') obj[d] = obj.data[d];
    }
    delete obj.data;
  }
}
console.log(obj);

Edit: When wanting to remove certain keys from an Object, simply use the delete keyword

var obj = {
  "results": {
    "grade": "A",
    "res": "fail",
    "marks": 12
  },
  "data": {
    details: {
      "name": "sam",
      "gender": "male",
      "age": 10
    }
  },
  "feespaid": "yes",
  "joindate": "sunday"
};
delete obj.results.res;
delete obj.data.details.gender;
delete obj.feespaid;
console.log(obj);

Answer №2

Here are two different approaches to achieve the same result:

obj.name = obj.data.name;
obj.age = obj.data.age;
delete obj.data;

Another method involves using a for-in loop:

for(item in obj.data) obj[item] = obj.data[item]; // Copy items from obj.data to obj
delete obj.gender;                                // Remove gender property
delete obj.data;                                  // Remove obj.data object

Check out this code snippet below:

var obj={
  "results":{
  "grade":"A",
  "marks":12
   },
  "data":{
   "name":"sam",
    "gender":"male",
   "age":10
  }
};

for(item in obj.data) obj[item] = obj.data[item];
delete obj.gender;
delete obj.data;

console.log(obj)

Answer №3

for (let extKey in object) {
    if(extKey === 'data') {
        for (let dataKey in object[extKey]) {
           object[dataKey] = object[extKey][dataKey];
        }
        delete object[extKey];
    }
}

(I will need to further explore the following solution) EDIT: To remove nested properties, you can use the code snippet below:

const invalidProperties = ['gender', 'feespaid']; //add more as needed
function deleteNestedProperties(obj) {
    for (let key in obj) {
        if(invalidProperties.includes(key)) {
            delete obj[key];
        } else {
            deleteNestedProperties(obj[key]);
        }
    }
}

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

Personalizing the arrow positioning of the Angular8 date picker (both top and bottom arrow)

I am interested in enhancing the design of the Angular 8 date picker by adding top and bottom arrows instead of the default left and right arrows. Can someone guide me on how to customize it? Check out the Angular 8 date picker here ...

The use of WebSockets in conjunction with text encoding techniques

After reviewing the material, I came across this information: The WebSocket API allows for the use of a DOMString object, which is transmitted in UTF-8 format, or it can also accept an ArrayBuffer, ArrayBufferView, or Blob objects for binary data transf ...

Tips for displaying a React component with ReactDOM Render

_Header (cshtml) <div id="Help"></div> export default class Help { ReactDOM.render( <Help/>, document.getElementById('Help') ); } Help.js (component) } My objective is to di ...

Adjust the styling with jQuery according to the selected value from the dropdown menu

Check out this Fiddle I have a jQuery script that is supposed to change the style of an input box to display:block if the selected value is "<>" (Between). However, currently it is changing the css for all selected items instead of just the target i ...

Updating embedded documents with new information in mongodb

After searching on SO, I couldn't find a satisfactory answer to my question related to working with mongodb and php for the past couple of weeks. So here I am seeking help. I have a database where I need to add new data to one of the embedded/nested d ...

What is the process for configuring NextJS to recognize and handle multiple dynamic routes?

Utilizing NextJS for dynamic page creation, I have a file called [video].tsx This file generates dynamic pages with the following code: const Video = (props) => { const router = useRouter() const { video } = router.query const videoData = GeneralVi ...

Issue with Vuex not functioning properly in Nuxt.js

I'm facing an issue with setting the state in Vuex on my Nuxt.js App. It seems to not be working correctly. So, here is how I am trying to set the state using the fetch method: fetch({app, store, route}) { app.$axios.$get(`apps/${route.params ...

"AngularJS Bi-Directional Data Binding Issue: Unexpected 'Undefined

Recently, I've been tackling a project that involves using a directive. Initially, everything was smooth sailing as I had my directive set up to bind to ngModel. However, I hit a roadblock when I needed to bind multiple values. Upon making the necessa ...

Automatically Trigger Knex.JS Updates

Utilizing the migration tools provided by Knex.JS, I am attempting to create a table with an automatically updating column named updated_at whenever a record is modified in the database. Take, for instance, this table: knex.schema.createTable('table ...

Experiencing difficulties with a click event function for displaying or hiding content

Struggling with implementing an onClick function for my two dynamically created components. Currently, when I click on any index in the first component, all content is displayed. What I want is to show only the corresponding index in the second component ...

Issue with zeroLineColor and zeroLineWidth not functioning properly for the x-axis within Chartjs

Looking to customize the width and color of the x-axis in Chartjs? While it's straightforward for the y-axis using zeroLineColor and zeroLineWidth, achieving the same effect for the x-axis seems trickier. If you try adding: ticks: { beginAtZero: tr ...

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 ...

Enhancing button functionality using jQuery and JavaScript for toggling behavior

I am facing a challenge with this code. The goal is to have a single script that can handle multiple audio elements on the page and toggle between PLAY and PAUSE buttons by adding or removing classes. Can anyone suggest any changes or additions that coul ...

What is the reason behind Meteor automatically updating a record without the need to run a "Meteor.call" function for an update?

I am currently developing a Meteor.js application and while I have grasped the basic concepts of Meteor, I feel like I might be missing something when it comes to its reactivity principles. Using angular-meteor, I am utilizing a $scope variable in my view ...

Creating dynamic properties in JavaScript based on another object is a powerful way to manipulate data

In my current scenario, I am faced with the task of creating a new object named result based on an existing object called source. This new object must contain all properties from source, and also include additional "methods" named after the properties to ...

Utilizing the parameter "error" to distinguish unsuccessful tasks within async.mapLimit

In my coding process, I am using async.mapLimit to implement some parallel operations on an array with a limit of 10: async.mapLimit(files, 10, function(file, callback) { ... etc... }, function(error, files) { ... etc.. }); Within the main opera ...

Inject JSON data into a JavaScript array

I am dealing with a JSON file in the following format: [{"excursionDay":"2"},{"excursionDay":"3"},{"excursionDay":"4"}] My goal is to extract the values of excursionDay and store them in an array in JavaScript like this: dayValues = [2,3,4] Here is m ...

smoothly hide the dropdown menu when a link is clicked with a transition effect

I am struggling with two bugs in my dropdown menu that I can't seem to fix. The navigation links on my homepage take users to different sections of the page instantly when clicked. However, the issue arises when the dropdown menu does not close after ...

Initially, calling angular.element(..).scope() will return undefined

I have encountered an issue where I am unable to access my angular controller's scope outside of the controller. This problem arises when using an external JavaScript library that performs certain actions and executes callbacks upon completion. In one ...

Firestore query is returning empty results upon page initialization, but provides data upon subsequent re-renders in React Native

ISSUE I'm encountering an issue where I am unable to fetch documents from a Firestore collection when the page loads. Despite executing the query multiple times during loading, it does not return any results. However, if I trigger the query by changi ...