0

I have an array of objects like this:

const data = [
  {name: 'Page A', count: 4000},
  {name: 'Page B', count: 3000},
  {name: 'Page C', count: 2000},
  ];

I need to add an index number to the count property so the list would look like this:

const wantedArray = [
  {name: 'Page A', count1: 4000},
  {name: 'Page B', count2: 3000},
  {name: 'Page C', count3: 2000},
  ];

I tried this but got this ts error: Operator '+' cannot be applied to types '{ name: any; count: any; }' and 'number'.ts(2365)

let wantedArray: any = []

data.map((object: any, index) => {
    wantedArray.push({
      name: object.name,
      count+index: start.count,
    });
  });

What is the best solution to achieve this? Thank you.

BorealBird
  • 13
  • 3

3 Answers3

0

Use bracket notation - [key] for the dynamic key.

const data = [{
    name: 'Page A',
    count: 4000
  },
  {
    name: 'Page B',
    count: 3000
  },
  {
    name: 'Page C',
    count: 2000
  },
];


const wantedArray = data.map((obj, index) => ({
  name: obj.name,
  [`count${index+1}`]: obj.count,
}));

console.log(wantedArray);
wangdev87
  • 8,611
  • 3
  • 8
  • 31
0

Simply assign wantedArray to map of the data array, also use [] to assign values with dynamic key.

const data = [
  {name: 'Page A', count: 4000},
  {name: 'Page B', count: 3000},
  {name: 'Page C', count: 2000},
  ];

let wantedArray = data.map((obj, index) => {
    return {
      name: obj.name,
      [`count${index+1}`]: obj.count
    }
 });
 console.log(wantedArray)
Abishek Kumar
  • 519
  • 5
  • 13
0

Use [variablename] to write inside a variable name.

And since the index starts at 0, we do + 1.

const data = [
  {name: 'Page A', count: 4000},
  {name: 'Page B', count: 3000},
  {name: 'Page C', count: 2000},
];

const result = data.map((n, i) => {
  return {
    name: n.name,
    [`count${i+1}`]: n.count,
  }
});

console.log(result);

Or if you want to push it into a new array.

const data = [
  {name: 'Page A', count: 4000},
  {name: 'Page B', count: 3000},
  {name: 'Page C', count: 2000},
];

let wantedArray = [];

data.forEach((object, index) => {
  return wantedArray.push({
    name: object.name,
    [`count${index+1}`]: object.count,
  });
});

console.log(wantedArray);
Tigran Abrahamyan
  • 756
  • 1
  • 4
  • 7