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

Creating a array using a string which contains the key and the value of the properties

本文关键字:字符串 创建 数组 键和值 包含 属性      更新时间:2023-09-26

我检查了任何相关的帖子,但没有找到。字符串没有问题,但我不知道如何实现它。
我需要把下面的字符串转换成一个对象。

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
  }
]

这样就可以了:

var a = "Integer,1 Float,2.0'nBoolean,True Integer,6'nFloat,3.66 Boolean,False";
var result = a.split(''n').map(function(item) { // Iterate over all objects
  var row = {};
  item.split(' ')
    .forEach(function(pair) {              // For each key/value pair in the current object
      var data = pair.split(',');          // Separate the key from the value
      if (data[0] === 'Boolean')           // If the current value is a boolean:
        row[data[0]] = data[1] === 'True'; // Get the proper boolean value
      else                                 // Otherwise:
        row[data[0]] = Number(data[1]);    // Get the numeric value.
    });
  return row;
});
console.log(result);

您可以使用对象来更好地将类型转换为您需要的类型,这对于新类型来说很容易维护。

var a = "Integer,1 Float,2.0'nBoolean,True Integer,6'nFloat,3.66 Boolean,False",
    types = {
        Integer: function (v) { return +v; },
        Float: function (v) { return +v; },
        Boolean: function (v) { return { True: true, False: false }[v]; },
        default: function (v) { return v; }
    },
    result = a.split(''n').map(function (row) {
        o = {};
        row.split(' ').forEach(function (item) {
            var data = item.split(',');
            o[data[0]] = (types[data[0]] || types.default)(data[1]);
        });
        return o;
    });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

您也可以这样做;

var s ="Integer,1 Float,2.0'nBoolean,True Integer,6'nFloat,3.66 Boolean,False",
    a = s.split("'n")
         .map(o => o.match(/([a-zA-Z]+),(['w'.]+)/g)
                    .reduce(function(p,c){
                    	      var pv = c.split(",");
                    	      return Object.assign(p,{[pv[0]]: +pv[1] ? +pv[1] : pv[1] !== "False"});
                            }, {}));
console.log(a);

首先需要一种解析预期文本的好方法。根据你的要求,我已经想出了一个解决办法。

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

抱歉我之前的回答。我没有仔细阅读问题。我从Cerbrus的回答中得到了一些帮助,但仍然无法匹配他的水平bravo。我让它变得简单,因为我只知道简单。

var obj = {};
var arr = []
var a ="Integer,1 Float,2.0'nBoolean,True Integer,6'nFloat,3.66 Boolean,False";
var aArray = a.split(''n')
for( var i=0 ; i < aArray.length; i++ )
        {  
          
           lilArray = aArray[i].split(" ");
           lillilArray1 = lilArray[0].split(',');
           lillilArray2 = lilArray[1].split(',');
           lla11        = lillilArray1[0];
           lla12        = lillilArray1[1];
           lla21        = lillilArray2[0];
           lla22        = lillilArray2[1];
           if(lla11 == "Boolean") 
              obj[lla11] = lla12 === 'True';
           else
              obj[lla11] = Number(lla12);
          if(lla21 == "Boolean") 
              obj[lla21] = lla22 === 'True';
           else
              obj[lla21] = Number(lla22);
           arr.push(obj); 
           obj={};  
       }
   console.log(arr);