简体   繁体   English

如何将字符串数组转换为 Javascript object?

[英]How to convert an array of string into a Javascript object?

Each user's information is separated by a comma, or a space, but some pieces of information can be blank.每个用户的信息以逗号或空格分隔,但有些信息可以留空。 I'm looking for a solution to take the user information and create an object (key-value mapping).我正在寻找一种解决方案来获取用户信息并创建一个 object(键值映射)。 Here's my approach, but I can't get multiple objects.这是我的方法,但我无法获得多个对象。

 function Person(name, email, age, occupation) { this.name = name; this.email = email; this.age = age; this.occupation = occupation; } let string = "Norbert,norbert@test.com,51,Coder Noemi,,,Teacher Rachel,rachel@test.com,," let stringArr = string.split(/[\s,]+/) const personObj = new Person(...stringArr) console.log(personObj)

When splitting the string, you need to keep the empty strings between the commas, but you are splitting sequences of commas as one divider - [\s,]+ .拆分字符串时,您需要在逗号之间保留空字符串,但您将逗号序列拆分为一个分隔符 - [\s,]+

Split the string by a single , or a sequence of spaces - /,|\s+/ .将字符串拆分为一个或一系列空格 - / , /,|\s+/ Then create an array of Person using Array.from() , dividing the original length by 4, and taking 4 properties by slicing the original array:然后使用Array.from()创建一个Person数组,将原始长度除以 4,并通过对原始数组进行切片来获取 4 个属性:

 function Person(name, email, age, occupation) { this.name = name; this.email = email; this.age = age; this.occupation = occupation; } const string = "Norbert,norbert@test.com,51,Coder Noemi,,,Teacher Rachel,rachel@test.com,," const stringArr = string.split(/,|\s+/) const personArr = Array.from({ length: stringArr.length / 4 }, (_,i) => new Person(...stringArr.slice(i * 4, i * 4 + 4)) ) console.log(personArr)

Assuming space is a line separator, and comma is a field separator, split:假设空格是行分隔符,逗号是字段分隔符,拆分:

 function Person(name, email, age, occupation) { this.name = name; this.email = email; this.age = age; this.occupation = occupation; } let string = "Norbert,norbert@test.com,51,Coder Noemi,,,Teacher Rachel,rachel@test.com,,"; const persons = string.split(' ').map(r => new Person(...r.split(','))); console.log(persons)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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