How to replace key in nested object

javascript rename object key
how to change key = value in object javascript
how to change json key name javascript

I have an object like this,

{
  id: '1',
  displaName: 'A',
  children: [
  {
    id: '2',
    displayName: 'B',
    children: [
    {
      id: '3',
      displayName: 'C',
      children: [
            //More nested array here
      ]
    }
    ]
  }]
}

I just want to change key displayName with label so that my object will look like this,

{
  id: '1',
  label: 'A',  //change key displayName => label
  children: [
  {
    id: '2',
    label: 'B',  //change key displayName => label
    children: [
    {
      id: '3',
      label: 'C',  //change key displayName => label
      children: [
            //More nested array here
      ]
    }
    ]
  }]
}

I have tried this but not able to replace key in nested array,

const newKeys = { displaName: "label"};
const renamedObj = renameKeys(resp.data, newKeys);
console.log(renamedObj);

function renameKeys(obj, newKeys) {
  const keyValues = Object.keys(obj).map(key => {
    console.log(key);
    let newKey = null
    if(key === 'displayName'){
       newKey = 'label'
    }else{
       newKey = key
    }
    console.log(newKey);
    return { [newKey]: obj[key] };
  });
  return Object.assign({}, ...keyValues);
}

Please help me sort out this.

Thanks in advance.

  1. You have typo in your code. Some variables are shown as displaName instead of displayName.

  2. You need to call a function recursively to work as you intended.

  3. You didn't used newKeys variable for renaming. You just have hard-coded it like newKey = 'label'. But this issue irrelevant with the problem.

const resp = {
  data: {
    id: '1',
    displayName: 'A',
    children: [{
      id: '2',
      displayName: 'B',
      children: [{
        id: '3',
        displayName: 'C',
        children: [
          //More nested array here
        ]
      }]
    }]
  }
}

const newKeys = {
  displayName: "label"
};
const renamedObj = this.renameKeys(resp.data, newKeys);
console.log(renamedObj);

function renameKeys(obj, newKeys) {
  const keyValues = Object.keys(obj).map(key => {
    let newKey = null
    if (key === 'displayName') {
      newKey = newKeys.displayName
    } else {
      newKey = key
    }
    if (key === 'children') {
      obj[key] = obj[key].map(obj => renameKeys(obj, newKeys));    
    }
    return {
      [newKey]: obj[key]
    };
  });
  return Object.assign({}, ...keyValues);
}

nested-keys, Description. make an un-nested object into a nested object by object keys Description. Recursively replace absolute paths in objects and arrays with ~  Most of the time when you are getting undefined, the object/array simply doesn't have a property with that name. Use console.log or console.dir and inspect the structure of object / array. The property you are trying to access might be actually defined on a nested object / array.

This is a really generic solution which will traverse through an object and update any object keys that are in the given object literal (keysToUpdate).

const orig = {
  id: '1',
  displayName: 'A',
  children: [{
    id: '2',
    displayName: 'B',
    children: [{
      id: '3',
      displayName: 'C',
      children: [
        //More nested array here
      ]
    }]
  }]
};

const updateDisplayNameToLabel = (val, keysMap) => {
  if (val == null) return null;
  if (Array.isArray(val)) {
    return val.map(item => updateDisplayNameToLabel(item, keysMap));
  } else if (typeof val == "object") {
    return Object.keys(val).reduce((obj, key) => {
      const propKey = updateDisplayNameToLabel(key, keysMap);
      const propVal = updateDisplayNameToLabel(val[key], keysMap);
      obj[propKey] = propVal;
      return obj;
    }, {});
  } else if (typeof val === "string") {
    return keysMap[val] || val;
  }
  return val;
}

const keysToUpdate = {
  displayName: 'label',
  children: 'items'
};

const updated = updateDisplayNameToLabel(orig, keysToUpdate);

console.log(updated);

nested object, Delete nested key-value pairs on an object with a provided key, or remove Remove recursively all key-value pairs where value is undefined replace-path   I am trying to access the key and values of my nested array like this: var obj = $.getJSON("mydata.json", function() { console.log( "load success" ); }); Object.keys

The existing answers are great, but I can't resist adding a JSON.stringify version:

const data = { id: '1', displayName: 'A', children: [ { id: '2', displayName: 'B', children: [ { id: '3', displayName: 'C', children: [] }] }] };
const result = JSON.parse(JSON.stringify(data).replace(/"displayName":/g, '"value":'));
console.log(result);

Clever/underscore.deep: Underscore utilities for operating , in the input object will be converted to nested objects, so if you use dots in your keys you may want to replace them before you call _.deepFromFlat . describe '_. You have a nested object tree. You must go through the full tree to reach your element. There might be a library out there that does this for you, but underneath it all, it will be traversing everything.

Updating a value in a nested array of objects, How could we change the value of just key in just one object? Step 1: Find the element. We first want to find the index in the array of the object, or  This way, the next level key will always be accessed from an object that exists or an empty object, but never from undefined. Unfortunately, you cannot access nested arrays with this trick. Access Nested Objects Using Array Reduce. Array reduce method is very powerful and it can be used to safely access nested objects.

Replace a nested json object in a json array only if exists, Name == "The Name")) { replace (Server, "New Serve"); // can also be Replace( Object.Name == "The Name", // ( // { // ApiKey: "The key parameter from Octopus",   Keys: In JavaScript, objects are used to store collection of various data. It is a collection of properties. A property is a “key:value” pair. Keys are known as ‘property name’ and are used to identify values. Method 1: Renaming the object by simple assignment of variables. After the assignment of variable or variables we will delete

javascript loop nested object Code Example, Get code examples like "javascript loop nested object" instantly right from for( let [key,val] in obj){ messageBody = messageBody.replace("{"+  key: “name” because it’s the first key from Object.keys(obj). renamedObject: undefined Also notice that we can access keysMap and obj from the parent function’s scope.