skip to Main Content

I have an array of objects as below

[
    {contactTypeField-0: 'Index0', firstNameField-0: '0', uniqueRowField-0: 0},
    {contactTypeField-1: 'Index1', firstNameField-1: '1', uniqueRowField-1: 0}
]

What is the best way to replace the keys i.e. I want to remove -0, -1, -2 from each of the keys. So I am expecting the output as

[
    {contactTypeField: 'Index0', firstNameField: '0', uniqueRowField: 0},
    {contactTypeField: 'Index1', firstNameField: '1', uniqueRowField: 0}
]

Is there some ES6 way to achieve this ?

4

Answers


  1. You could simply use regex like this:

    const data = [
      { 'contactTypeField-0': 'Index0', 'firstNameField-0': '0', 'uniqueRowField-0': 0 },
      { 'contactTypeField-1': 'Index1', 'firstNameField-1': '1', 'uniqueRowField-1': 0 }
    ];
    
    const updatedData = data.map(obj => {
      const updatedObj = {};
      Object.entries(obj).forEach(([key, value]) => {
        const newKey = key.replace(/-d+$/, '');
        updatedObj[newKey] = value;
      });
      return updatedObj;
    });
    
    console.log(updatedData);
    Login or Signup to reply.
  2. You can use Array#map to transform the array of objects to a new array.

    For each object, map over its entries and use String#replace to remove the required suffix (the regular expression -d+$ matches a hyphen and one or more consecutive digits directly preceding the end of the string). Finally, use Object.fromEntries to convert the array of key-value pairs back to an object.

    const arr=[{"contactTypeField-0":"Index0","firstNameField-0":"0","uniqueRowField-0":0},{"contactTypeField-1":"Index1","firstNameField-1":"1","uniqueRowField-1":0}];
    const res = arr.map(o => Object.fromEntries(Object.entries(o)
                    .map(([k, v]) => [k.replace(/-d+$/, ''), v])));
    console.log(res);
    Login or Signup to reply.
  3. You could create a reusable function that can prune keys of an object using a "prune" function i.e. pruneFn.

    const original = [
      { 'contactTypeField-0': 'Index0', 'firstNameField-0': '0', 'uniqueRowField-0': 0 },
      { 'contactTypeField-1': 'Index1', 'firstNameField-1': '1', 'uniqueRowField-1': 0 }
    ];
    
    const pruneKeys = (items, pruneFn) => items
      .map(data => Object.fromEntries(Object.entries(data)
        .map(([key, value]) => [pruneFn(key), value])));
    
    const pruned = pruneKeys(original, (key) => key.replace(/-d+$/, ''));
    
    console.log(pruned);
    .as-console-wrapper { top: 0; max-height: 100% !important; }

    You could even throw an error, if a key is illegal:

    const original = [
      { 'contactTypeField-0': 'Index0', 'firstNameField-0': '0', 'uniqueRowField-0': 0 },
      { 'contactTypeField-1': 'Index1', 'firstNameField-99': '1', 'uniqueRowField-1': 0 }
    ];
    
    const pruneKeys = (items, pruneFn) => items
      .map((data, index) => Object.fromEntries(Object.entries(data)
        .map(([key, value]) => [pruneFn(key, index), value])));
    
    const pruned = pruneKeys(original, (key, expectedIndex) => {
      const [, newKey, actualIndex] = key.match(/(.+)-(d+)$/);
      if (+actualIndex !== expectedIndex) {
        throw new Error(`Expected index: ${expectedIndex}, but received ${actualIndex} for ${key}`);
      }
      return newKey;
    });
    
    console.log(pruned);
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    Login or Signup to reply.
  4. One more way with Object.entries and reduce

    const data = [
      {
        "contactTypeField-0": "Index0",
        "firstNameField-0": "0",
        "uniqueRowField-0": 0,
      },
      {
        "contactTypeField-1": "Index1",
        "firstNameField-1": "1",
        "uniqueRowField-1": 0,
      },
    ];
    
    const res = data.map((obj) =>
      Object.entries(obj).reduce(
        (acc, [key, val]) => ({ ...acc, [key.split("-")[0]]: val }),
        {}
      )
    );
    
    console.log(res);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search