字符串数组转换成对象数组

时间:2019-08-22 10:19:11

标签: javascript

所以我在JS中有一个这样的字符串数组:

['07-01-16  06:55AM                   57 100313_1_1_065215.bad',
  '07-01-16  07:03AM                   57 100313_1_1_070315.bad',
  '07-01-16  07:26AM                   61 100313_1_1_072315.bad',
...]

,并希望成为一个对象数组,因此我可以按以下两个第一字段进行排序:

{ date: '07-01-16',
  hour: '07:03AM'
  size: '67' 
 name: '100359_1_1_112700.bad'
}
{ name: '101105_1_1_200026.bad',
...}

2 个答案:

答案 0 :(得分:7)

我将使用RegExp进行映射和拆分:

const array = [
  '07-01-16  06:55AM                   57 100313_1_1_065215.bad',
  '07-01-16  07:03AM                   57 100313_1_1_070315.bad',
  '07-01-16  07:26AM                   61 100313_1_1_072315.bad'
];

const result = array.map((str) => {
  const [ date, hour, size, name ] = str.split(/\s+/);
  return { date, hour, size, name };
});

console.log(result);
.as-console-wrapper {min-height: 100%}

答案 1 :(得分:0)

您尝试我的代码:

const arr = [
  '07-01-16  06:55AM                   57 100313_1_1_065215.bad',
  '07-01-16  07:03AM                   57 100313_1_1_070315.bad',
  '07-01-16  07:26AM                   61 100313_1_1_072315.bad']

let result = arr.map(item =>{
  let values = item.replace(/  +/g, ' ').split(" ")

  return { date: values[0],
     hour: values[1],
     size: values[2], 
     name: values[3]
   }
})

console.log(result)
.as-console-wrapper {min-height: 100%}