0

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?

Wing Shum
  • 472
  • 6
  • 19
  • It's an array of objects. – Nik Jan 29 '21 at 06:42
  • Does this answer your question? [Remove property for all objects in array](https://stackoverflow.com/questions/18133635/remove-property-for-all-objects-in-array) – Nik Jan 29 '21 at 06:43
  • You can loop through the array with a ```forEach``` then use the ```delete``` operator to. delete the key/value pair you want – Kyle Lambert Jan 29 '21 at 06:44

2 Answers2

1

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;
});
Matt
  • 3,677
  • 1
  • 14
  • 24
  • Hi, it is returning TypeError: address.forEach is not a function, Why is that? – Wing Shum Jan 29 '21 at 06:49
  • Hi Matt, thank you for your time, I've checked it, typeof address is string instead of object, it must be because I've JSON.stringify it before, however, if its currently string, how can I change it back to object? – Wing Shum Jan 29 '21 at 06:55
  • 1
    You can't do much with a string. Use `JSON.parse(address)` to convert it back. – Matt Jan 29 '21 at 06:57
1

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.
SandyKrish
  • 222
  • 1
  • 11