将对象的字符串转换为对象的元素 [英] Transform string of objects into elements of object

查看:86
本文介绍了将对象的字符串转换为对象的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的对象字符串,如下所示.

I have this below string of objects as shown below.

[0,5]
   0: "A123  G  2323232"
   1: "F345  G  345667"
   2: "T677  G  -34343"
   3: "G454  G  4343"
   4: ""

如您所见,"A123 G 2323232"是一个字符串,其中包含制表符分隔的值.

As you can see "A123 G 2323232" is a string which has tab seperated values in it.

我想要一个如下的最终输出.

I would like to have a final output as follows.

[0,4]
   0: 
     UserId:A123
     Type:  G
     Values: 2323232
   1: 
     UserId: F345  
     Type:  G
     Values: 345667
   2: 
     UserId: T677  
     Type:  G
     Values: -34343
   3: 
     UserId: G454  
     Type:  G
     Values: 4343

请注意.第四个元素是空字符串.因此它不应转换为最终数据.

Please note. the 4th element is empty string. so it should not transform to final data.

任何人都可以建议如何将其分发到不同的元素.

Can anyone please suggest how to distribute this to different elements.

推荐答案

您可以匹配非空格部分并将数组解构为所需的属性并返回一个对象.

You could match non space parts and deconstruct the array to the wanted properties and return an object.

var data = ["A123  G  2323232", "F345  G  345667", "T677  G  -34343", "G454  G  4343", ""],
    result = data
        .filter(Boolean)
        .map(s => {
            var [UserId, Type, Values] = s.match(/[^ ]+/g);
            return { UserId, Type, Values };
        });
                
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于将对象的字符串转换为对象的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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