javascript - 将字符串数组转换为对象
问题描述
我有一个字符串数组,每个字符串都包含逗号分隔的值。
我想把它转换成一个对象数组。
例如,我有:
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和扩展运算符。但似乎必须有一种更简单的方法来使用解构或其他方法来做到这一点。
解决方案
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));
推荐阅读
- java - IBM MobileFirst 平台适配器到 Java 中的适配器调用不支持 utf-8 或(阿拉伯语)作为响应
- ruby-on-rails - 为非管理员用户设置不同的路由页面(属性)(在 ruby on rails 上设计 gem)
- maven - 列出存储库中工件的用户
- android - 活动未开始,无法解析 Intent { act="android.search.action.GLOBAL_SEARCH" }
- python - 如何在django中检查for循环的重复行
- mysql - 如何以最佳方式按两列进行 GROUP BY 和计数?
- html - 我不明白 C++ 和 HTML 在一段代码中的合并
- c# - 为什么不从安装程序执行 sql 作业?
- reactjs - 如何在 react-bootstrap 中使用多选下拉菜单
- r - 在R中将长格式平面文件转换为宽格式