Home > Back-end >  Easy way to remove duplicates form an object in apps script
Easy way to remove duplicates form an object in apps script

Time:01-07

I have an object as below,

name_details = { 'Quantity based detail': 'X13', 'Comms excess': 'X14' , 'normal_detail': 'X15', 'Flat_detail': 'X16', 'Quantity based detail': 'X17'}

I want the output to be as below

name_details = { 'Quantity based detail': 'X13', 'QBD:' 'Comms excess': 'X14' , 'normal_detail': 'X15', 'Flat_detail': 'X16'}

Where ever the key is same, delete the later entry from the object to have only unique keys in the object.

I know a short way to do this for an array as below, but not sure for an object

var new_array = [...new Set(old_array)];

Please help how can I achieve this with less lines of code for the object.

Thank you

CodePudding user response:

Field names are always unique in a JavaScript object. In other words, there is always exactly one occurrence of each field name, and you will never see an object that repeats field names as in { 'Quantity based detail': 'X13', 'Quantity based detail': 'X17' }.

If you need to make sure that certain fields always appear, and want to assign default values to those fields, use this pattern:

function test() {
  const name_details = { 'Quantity based detail': 'X13', 'Comms excess': 'X14', 'normal_detail': 'X15', 'Flat_detail': 'X16' };
  const defaults = { 'Missing detail': 42, 'Quantity based detail': 'qbd default', 'Comms excess': 'whatever', 'normal_detail': 'whatever', 'Flat_detail': 'whatever' };
  const finalNameDetails = Object.assign(defaults, name_details);
  console.log(JSON.stringify(finalNameDetails, null, 2));
}

See Clean Code JavaScript.

  • Related