Gurmukh Singh
Gurmukh Singh

Reputation: 2017

delete object element within an array

I have an object, and within the object, i need to delete the address from the array of objects using javascript.

 obj = {
        "name":1,
        "Details":[
            {
              "mname":"text here",
              "sname":"text here",
              "address":"text",
              "saddress":"text"
            }
        ]
      }

I have tried the following, but no luck:

delete obj.Details.address

and

delete obj.Details[0].address

Upvotes: 0

Views: 46

Answers (3)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

If you want to delete the adress property of all the objects inside the Details array, then do it using forEach like this:

obj.Details.forEach(function(detail) {
    delete detail.address;
});

Or using an old for loop like this:

for(var i = 0; i < obj.Details.length; i++) {
    delete obj.Details[i].adress;
}

Upvotes: 1

jjj
jjj

Reputation: 1154

your object structure is wrong

  obj = {
    "name":1,
    "Details":[
        {
          "mname":"text here",
          "sname":"text here",
          "address":"text",
          "saddress":"text"
        }
    ]
  }

it should be "address":"text", in string format then

delete obj.Details[0].address

will work.

Upvotes: 3

xale94
xale94

Reputation: 424

Are you sure this don't work?

delete obj.Details[0].address

I've just tried in the chrome console and this works. Maybe you're not debugging correctly

Upvotes: 1

Related Questions