Skip to content Skip to sidebar Skip to footer

Creating A Array Using A String Which Contains The Key And The Value Of The Properties

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

Solution 1:

This'll do the trick:

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 objectsvar row = {};
  item.split(' ')
    .forEach(function(pair) {              // For each key/value pair in the current objectvar data = pair.split(',');          // Separate the key from the valueif (data[0] === 'Boolean')           // If the current value is a boolean:
        row[data[0]] = data[1] === 'True'; // Get the proper boolean valueelse// Otherwise:
        row[data[0]] = Number(data[1]);    // Get the numeric value.
    });

  return row;
});

console.log(result);

Solution 2:

You could use an object for better converting types to the type you need, which is easily to maintain for new types.

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

Solution 3:

You might possibly do as follows as well;

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(",");
                    	      returnObject.assign(p,{[pv[0]]: +pv[1] ? +pv[1] : pv[1] !== "False"});
                            }, {}));
console.log(a);

Solution 4:

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

Solution 5:

Sorry for my previous answer. I didn't read the question carefully. I have took some help from Cerbrus's answer and still can't match his level bravo. I have made it simple because i only know simple.

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

Post a Comment for "Creating A Array Using A String Which Contains The Key And The Value Of The Properties"