-4

I have a nested array like this:

var array = [["k001" , "water bottle", 5] , ["k002" , "doll" , 7] , ["k003" , "lollipop" , 2] ];

I want to turn this array into an object like this:

products = 
      {
         item1 : ["k001" , "water bottle", 5],
         item2 : ["k002" , "doll" , 7],
         item3 : ["k003" , "lollipop" , 2]

      }

Any help would be appreciated, thank you.

  • 2
    Does this answer your question? [Convert Array to Object](https://stackoverflow.com/questions/4215737/convert-array-to-object) – Namaskar Mar 19 '21 at 13:11
  • 1
    creating an object with properties like `item1`, `item2`, ... is an antipattern. – trincot Mar 19 '21 at 13:12
  • Familiarize yourself with [how to access and process nested objects or arrays](/q/11922383/4642212) and how to [create objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods) methods (both static and on prototype). You will likely realize that this is unnecessary and the wrong way around. – Sebastian Simon Mar 19 '21 at 13:12
  • 1
    Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan Mar 19 '21 at 13:12
  • What have you tried so far? Pls show us your attempt. – Nguyễn Văn Phong Mar 19 '21 at 13:19
  • I have tried @Sven Writes Code link and it has worked so far, thank you. I will also take a look at what others have suggested as well – NoobCoder254 Mar 19 '21 at 13:26

1 Answers1

0

You can use Array#reduce

var array = [["k001" , "water bottle", 5] , ["k002" , "doll" , 7] , ["k003" , "lollipop" , 2] ];

const result = array.reduce((acc, curr, index) => {
  const key = `item${index + 1}`;
  acc[key] = curr;
  return acc;
}, {});
console.log(result);

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56