-1

Take a look at this function:

//prices is an array of numbers

function mapPrices(prices) {
  let newArray = [];
  for (let i = 0; i < prices.length; i++) {
    newArray.push({ i: prices[i] });
  }
  return newArray;
}

If I run mapPrices([1,2,3,4]), I expect to get:

[{0: 1}, {1: 2}, {2: 3}, {3: 4}]

instead, I am getting:

[{"i": 1}, {"i": 2}, {"i": 3}, {"i": 4}]

Why?

How can I get what I want?

Bad At Cpp
  • 35
  • 6
  • 2
    This is how objects work: `{ i: 'foo' }` is syntactic sugar for a key named `"i"`. You probably want `{ [i]: 'foo' }`. – Dave Newton Aug 26 '21 at 15:28

1 Answers1

3
newArray.push({ i: prices[i] });

Here i is read as the key, so it's used as string.

Since you want the value of i, you'll need to use [] brackets to let JS know it's a variable:

newArray.push({ [i]: prices[i] });

function mapPrices(prices) {
  let newArray = [];
  for (let i = 0; i < prices.length; i++) {
    newArray.push({ [i]: prices[i] });
  }
  return newArray;
}

const res = mapPrices([1,2,3,4]);
console.log(res);

More info, also about the history with ES6; please take a look at

0stone0
  • 34,288
  • 4
  • 39
  • 64