Wing Shum
Wing Shum

Reputation: 492

How to remove a key in object in array

I have an address that looks like this

let address = [{"_id":"6013a6ef20f06428741cf53c","address01":"123","address02":"512","postcode":"23","state":"512","country":"32","key":1},{"_id":"6013a6eh6012428741cf53c","address01":"512","address02":"6","postcode":"6612","state":"33","country":"512","key":2}]

How can I remove '_id' and 'key' together with its Key and Value Pair.

And can you please let me know how does this type of array is called? Is it called Object in Array? I keep seeing this type of array but I have no clue how to deal with this, is there like a cheatsheet to deal with?

Upvotes: 0

Views: 2184

Answers (2)

SandyKrish
SandyKrish

Reputation: 232

First, this type of array is called "Array of Objects" (objects inside array)

Second, you can generate new set of array by delete the key which you want to remove by,

let newSetOfArray = address.map((obj)=> {
    delete obj._id;
    delete obj.key;
    return obj;
});

console.log(newSetOfArray);    // this array of objects has keys with absence of _id & key.

Upvotes: 1

Matt
Matt

Reputation: 3760

You can access the property of the object like this:

address[0]["_id"]
// or
address[0]._id

and you can delete the property like this:

delete address[0]["_id"]
// or
delete address[0]._id

Where 0 is the 1st index of the array. You might need to iterate over your array and remove the property from each object:

address.forEach(a => {
    delete a._id;
    delete a.key;
});

Upvotes: 1

Related Questions