Home > database >  Replace array in object with object in TypeScript
Replace array in object with object in TypeScript

Time:12-15

I have a huge JSON that I need to load. I'm trying to reduce the size of it by using arrays within the objects, but I don't find a proper way to back-translate it in Typescript.

Instead of repeating the dates in every object of this array, I thought I use a column called "values" and use typescript to assign the dates again.

This is what I'm retrieving:

  const rows = [
    {
      'name': '100100',
      'description': 'Dummy 00',
      'hierarchy': ['Final_Hierarchy'],
      'id': 0,
      'values': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
    }
  ];

  const columns = [
    '2022-09-18',
    '2022-09-25',
    '2022-10-02',
    '2022-10-09',
    '2022-10-16',
    '2022-10-23',
    '2022-10-30',
    '2022-11-06',
    '2022-11-13',
    '2022-11-20',
    '2022-11-27',
    '2022-12-04',
  ];

And this is what I need:

  const rows = [
    {
      'name': '100100',
      'description': 'Dummy 00',
      'hierarchy': ['Final_Hierarchy'],
      'id': 0,
      '2022-09-18': 0,
      '2022-09-25': 0,
      '2022-10-02': 0,
      '2022-10-09': 0,
      '2022-10-16': 0,
      '2022-10-23': 0,
      '2022-10-30': 0,
      '2022-11-06': 0,
      '2022-11-13': 0,
      '2022-11-20': 0,
      '2022-11-27': 0,
      '2022-12-04': 0,
    },
  ];

I tried this, but it returns "No index signature with a parameter of type 'string' was found on type '{}'".

var result = {};
  columns.forEach((key, i) => result[key] = rows.values[i]);

Does anyone have a solutions for this?

CodePudding user response:

Your code has the good idea you just forgot that rows is an array and that you want to change the first item so try:

columns.forEach((key, i) => result[key] = rows[0].values[i]);

CodePudding user response:

the first issue is you're trying to access an value of the rows object within the array without first specifying which index of the array you want to access. The next is that typescript is trying to tell you that the key on the object you're trying to assign doesn't exist.

const rows = [
    {
        'name': '100100',
        'description': 'Dummy 00',
        'hierarchy': ['Final_Hierarchy'],
        'id': 0,
        'values': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
    }
];

const columns = [
    '2022-09-18',
    '2022-09-25',
    '2022-10-02',
    '2022-10-09',
    '2022-10-16',
    '2022-10-23',
    '2022-10-30',
    '2022-11-06',
    '2022-11-13',
    '2022-11-20',
    '2022-11-27',
    '2022-12-04',
];

interface Result {
    [key: string]: number | string | string[];
}

let result: Result = {};

result['name'] = rows[0]['name'];
result['description'] = rows[0]['description'];
result['hierarchy'] = rows[0]['hierarchy'];
result['id'] = rows[0]['id'];

columns.forEach((key, i) => {
    result[key] = rows[0]['values'][i];
})

console.log(result);
  • Related