使用包含键和属性值的字符串创建数组 [英] Creating a array using a string which contains the key and the value of the properties

查看:44
本文介绍了使用包含键和属性值的字符串创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了任何相关信息,但找不到任何相关信息。字符串没有问题,但我不知道如何实现。

我需要将以下字符串转换为对象。

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);

这篇关于使用包含键和属性值的字符串创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆