使用包含键和属性值的字符串创建数组

编程入门 行业动态 更新时间:2024-10-28 10:32:55
本文介绍了使用包含键和属性值的字符串创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我检查了任何相关信息,但找不到任何相关信息。字符串没有问题,但我不知道如何实现。 我需要将以下字符串转换为对象。

I checked for any related posts but couldn't find any. There is no problem with the string but I can't figure out how to implement it. I need to convert the following string into a object.

var a ="Integer,1 Float,2.0\nBoolean,True Integer,6\nFloat,3.66 Boolean,False";

进入

[ { "Integer":1, "Float":2.0 }, { "Boolean":true, "Integer":6 }, { "Float":3.66, "Boolean":false } ]

推荐答案

首先,您需要一种解析所需文本的好方法。 对于您提供的内容,我提供了解决方案。

first you need a good way to parse the expected text. For what you provided I have come up with a solution.

var jsonString = "Integer,1 Float,2.0\nBoolean,True Integer,6\nFloat,3.66 Boolean,False"; var keyValArray = jsonString.split(/[\n]/g); // Need to parse the string. var result = []; // result object to keep new object. keyValArray.forEach(function(kv, i, a) { let obj = {}; kv.split(' ').forEach(function(k) { var key = k.split(',')[0]; let val = k.split(',')[1]; if(isNaN(val)) { val = val.toLowerCase() === "true" ? true : false; } else { val = Number(val); } obj[key] = val; }); result.push(obj); }); console.log('result : '); console.info(result);

更多推荐

使用包含键和属性值的字符串创建数组

本文发布于:2023-07-16 13:27:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1122193.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!