js数组字符串转成数组套对象
时间: 2023-12-09 14:36:51 浏览: 88
js将类数组对象转换成数组对象
可以使用JSON.parse()方法将字符串转换为JavaScript对象,然后再将对象放入数组中。例如:
```javascript
let str = '[{"name":"John", "age":30, "city":"New York"}, {"name":"Jane", "age":25, "city":"San Francisco"}]';
let arr = JSON.parse(str);
console.log(arr); // 输出:[{"name":"John", "age":30, "city":"New York"}, {"name":"Jane", "age":25, "city":"San Francisco"}]
```
如果要将一个字符串数组转换为数组套对象,可以使用map()方法遍历字符串数组,然后在map()方法中使用JSON.parse()方法将每个字符串转换为对象,最后返回一个新的数组。例如:
```javascript
let strArr = ['{"name":"John", "age":30, "city":"New York"}', '{"name":"Jane", "age":25, "city":"San Francisco"}'];
let arr = strArr.map(str => JSON.parse(str));
console.log(arr); // 输出:[{"name":"John", "age":30, "city":"New York"}, {"name":"Jane", "age":25, "city":"San Francisco"}]
```
阅读全文