Home > Mobile >  how to get values by nested object keys in array of objects
how to get values by nested object keys in array of objects

Time:10-12

I wrote a function which gets data of generic object and properties(keys) which values should be returned:

resultToArray<T>(
      data: T[],
      prop: (keyof T | ((row: T) => string))[] = []
  ): string[][] {

    // data: [{id: 1, name: 'first'}, {id: 2, name: 'second'}] -> [[1, 'first'], [2, 'second']]
    // prop: ['id', 'name']
    if (prop.length === 0) {
      return data.map(Object.values);
    } else {
      const output = data.map(d => {
        const a: string[] = [];
        for (let i = 0; i < prop.length; i  ) {
          a.push(d[prop[i]])
        }
        return a;
      });

      return output
    }
  }

Example Input:
data -

[ 
    { name: 'Name', address: 'Address', branch: { locale: 'Locale' } },
    { name: 'Name2', address: 'Address2', branch: { locale: 'Locale2' } }
]


prop - [ 'name', (d) => d.branch.locale ]

Output should be [['Name', 'Locale'], ['Name2', 'Locale2']]

Function works fine for simple keys, but for nested keys is not working

CodePudding user response:

You will need to check if the "prop" you want to extract is a function and invoke it.

for (let i = 0; i < prop.length; i  ) {
  const propToUse = prop[i];
  let value;
  if (typeof propToUse === 'function') {
    value = propToUse(d);
  } else {
    value = d[propToUse];
  }
  a.push(value);
}

CodePudding user response:

I believe a simple solution (tested with pure js) would be to check the type of prop[i] and split what functionality is used.

for (let i = 0; i < prop.length; i  ) {
  if (typeof prop[i] === 'string') {
    a.push(d[prop[i]]);
  } else {
    a.push(prop[i](d));
  }
}

You have to run the function with the data as a parameter to actually get the output.

Input:

resultToArray(
  [
   { name: 'Name', address: 'Address', branch: { locale: 'Locale' , extra: { data: 'Country1' } } },
   { name: 'Name2', address: 'Address2', branch: { locale: 'Locale2', extra: { data: 'Country2' } } }
  ],
  [ 'name', (d) => d.branch.locale, (d) => d.branch.extra.data ]
);

Output:

[
   [ 'Name', 'Locale', 'Country1' ],
   [ 'Name2', 'Locale2', 'Country2' ]
]
  • Related