Exclusion of Object Id

Asked

Viewed 31 times

3

I have the following object:

objTeste = [
  {
    "id": "03",
    "nome": "teste03",
    "pai": {
      "id": "02",
      "nome": "teste02",
      "pai": {
        "id": "01",
        "nome": "teste01"
      }
    }
  }
]

I want to remove all the Ids of this object with Javascript, I’ve tried with for but I can’t delete the last ID. Can someone help me?

  • 1

    You could add the code you have so far?

1 answer

5


This objTeste is an array of objects. To remove depth properties on a precise object from a recursive function, that is, to call itself at each sub-level to the object.

I created one that checks if a property is a sublevel (other object) and if it is not checked if the property is id. In case it’s deleted.

function recursiva(obj) {
    for (var k in obj) {
        if (typeof obj[k] == "object" && obj.hasOwnProperty(k)) recursiva(obj[k]);
        else if (k == 'id') delete obj.id;
    }
}
objTeste.forEach(recursiva);

jsFiddle: https://jsfiddle.net/93m66tx7/

In this case you don’t even need to use the .map for once changing the object within the array it changes directly in the original.


If you want to create a new array with new objects (without the ID):

function recursiva(obj) {
    var _obj = {};
    for (var k in obj) {
        if (typeof obj[k] == "object" && obj.hasOwnProperty(k)) _obj[k] = recursiva(obj[k]);
        else if (k != 'id') _obj[k] = obj[k];
    }
    return _obj;
}
var novo = objTeste.map(recursiva);
console.log(JSON.stringify(novo)); // [{"nome":"teste03","pai":{"nome":"teste02","pai":{"nome":"teste01"}}}]

jsFiddle: https://jsfiddle.net/93m66tx7/1/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.