首页 > 解决方案 > 将字符串数组转换为对象

问题描述

我有一个字符串数组,每个字符串都包含逗号分隔的值。

我想把它转换成一个对象数组。

例如,我有:

var myarray = [
 "a1,b1,c1,d1",
 "a2,b2,c2,d2",
 "a3,b3,c3,d3"
]

...最终应该是:

[
  {
    "field1": "a1",
    "field2": "b1",
    "field3": "c1",
    "field3": "d1"
  },
  {
    "field1": "a2",
    "field2": "b2",
    "field3": "c2",
    "field2": "d2"
  },
  {
    "field1": "a3",
    "field2": "b3",
    "field3": "c3",
    "field3": "d3"
  },
]

我尝试了各种方法,例如Object.assign和扩展运算符。但似乎必须有一种更简单的方法来使用解构或其他方法来做到这一点。

标签: javascriptdestructuring

解决方案


var myarray = [
 "a1,b1,c1,d1",
 "a2,b2,c2,d2",
 "a3,b3,c3,d3"
];

const makeProperties = arr => arr.map(item => item.split(',').reduce((result, splitItem, index) => {
  result['field' + (index + 1)] = splitItem;
  return result;
}, {}));

console.log(makeProperties(myarray));

这是一个使用单词表示数字的演示

var myarray = [
 "a1,b1,c1,d1",
 "a2,b2,c2,d2",
 "a3,b3,c3,d3"
];

const numbers = ['one', 'two', 'three', 'four'];

const makeProperties = arr => arr.map(item => item.split(',').reduce((result, splitItem, index) => {
  result[numbers[index]] = splitItem;
  return result;
}, {}));

console.log(makeProperties(myarray));


推荐阅读