1

const arr = [
  [1, "string1", 'string11'],
  [2, "string2", 'string22'],
  [3, "string3", 'string33'],
  [4, "string4", 'string44'],
];
const obj = arr.reduce((acc, val) => {
  for (let i = 0; i < val.length; i += 3) {
    acc[val[i]] = {
      val: val[i + 2]
    }
  }
  return acc;
}, {});
console.log(obj);
output is :
1: Object
val: "string11"
2: Object
val: "string22"
3: Object
val: "string33"
4: Object
val: "string44"

I want to replace val: val[i+2] to val[i+1]: val[i+2] to make the object to be

1: Object
"string1": "string11"
2: Object
"string2": "string22"
3: Object
"string3": "string33"
4: Object
"string4": "string44"

But this syntax is incorrect val[i+1]: val[i+2], can someone please tell me how to make val to be dynamic?

olo
  • 5,225
  • 15
  • 52
  • 92
  • @CertainPerformance - it's the opposite of that, OP wants a dynamic key when creating the object. I'll dig up the other dupe. – VLAZ Aug 20 '19 at 08:02
  • Real dupe: https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name – VLAZ Aug 20 '19 at 08:03

1 Answers1

2

You can use compute name property of ES6 to set property name from a variable by simply wrapping with bracket.

const arr = [
  [1, "string1", 'string11'],
  [2, "string2", 'string22'],
  [3, "string3", 'string33'],
  [4, "string4", 'string44'],
];
const obj = arr.reduce((acc, val) => {
  for (let i = 0; i < val.length; i += 3) {
    acc[val[i]] = {
      [val[i + 1]]: val[i + 2]
   //-^^^^^^^^^^^^---- here
    }
  }
  return acc;
}, {});
console.log(obj);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 1
    Thanks for the answer! I tried to wrap them in `{}` but didn't work. The key needs to be wrapped by square brackets `[]` – olo Aug 20 '19 at 08:05