0

I'm trying to get the values from an array of numbers as values in the dictionary/object.

const array = [5,4,2,1]
const funct = (arr) => {
  const dict = {}
  for (i = 0; i < arr.length; i++) {    
    `dict.field${i+1}` = arr[i]
  }
  return console.log(dict);
}

funct(array);

I expect to have dict = {field1:5, field2:4, field3:2, field4:1}

How can I do it?

1 Answers1

0

Use the computed property access syntax (aka. bracket notation) to access or set a property of an object:

const array = [5,4,2,1]
const funct = (arr) => {
  const dict = {}
  for (i = 0; i < arr.length; i++) {    
    dict[`field${i+1}`] = arr[i]
  }
  return console.log(dict);
}

funct(array);
FZs
  • 16,581
  • 13
  • 41
  • 50