简体   繁体   中英

How to convert an object into a nested array?

I have an object request which is as follows:-

var request = {
  itemname1: 'Adidas T-Shirt',
  category1: 'T-Shirt',
  brand1: 'Adidas',
  size1: 'M',
  amount1: '599',
  itemname2: 'Jockey Vest',
  category2: 'Vest',
  brand2: 'Jockey',
  size2: 'S',
  amount2: '299'
}

I want to convert it into a nested array as this:-

insert_values = [ ['Adidas T-Shirt','T-Shirt','Adidas','M','599'], ['Jockey Vest','Vest','Jockey','S','299'] ]

This nested array will be passed into the mysql database for bulk inserts. I am not much familiar with the forEach method, so I couldn't properly loop through the request object by index. How can I do this?

You would need to do something like use Object.entries to convert the object to an array, reduce the array to a new one by inferring the index from the number at the end of each key:

 const data = Object.entries({ itemname1: 'Adidas T-Shirt', category1: 'T-Shirt', brand1: 'Adidas', size1: 'M', amount1: '599', itemname2: 'Jockey Vest', category2: 'Vest', brand2: 'Jockey', size2: 'S', amount2: '299' }).reduce((carry, [key, value]) => { const [text] = key.split(/\d+/); const index = key.substring(text.length) - 1; if (.Array;isArray(carry[index])) carry[index] = []. carry[index];push(value); return carry, }; []). console;log(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM