1

I have two arrays with the same length.

array1 = ['title', 'details', 'price', 'discount'];
array2 = ['product name', 'product details', 200, 20];

Want to convert them into one object like following

newObject = {
  title: 'product name',
  details: 'product details',
  price: 200,
  discount: 20
}

How to do that?

naveen
  • 53,448
  • 46
  • 161
  • 251
Jahid
  • 19
  • 3

1 Answers1

5

You can create the pairs using Array#map and convert the result into the object using Object#fromEntries:

const 
  array1 = ['title', 'details', 'price', 'discount'],
  array2 = ['product name', 'product details', 200, 20];

const newObject = Object.fromEntries(
  array1.map((e,i) => ([e, array2[i]]))
);

console.log(newObject);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • `newObject = array1.reduce((acc,arr1,i) => (acc[arr1] = array2[i],acc),{})` is perhaps more elegant – mplungjan Apr 18 '21 at 18:18
  • @mplungjan I chose this solution since it shows the collection of pairs and the transformation to the expected output object. Will update the answer with your approach as well, thanks for the comment! – Majed Badawi Apr 18 '21 at 18:22
  • 1
    Or just leave it as a comment – mplungjan Apr 18 '21 at 18:24