Transform String Of Objects Into Elements Of Object
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: '' As you can see '
Solution 1:
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; }
Solution 2:
You can split each string into its individual pieces of data, and then map those pieces into an object with the properties you want. Here's what it would look like:
var data = ["A123 G 2323232","F345 G 345667","T677 G -34343","G454 G 4343", ""];
/* ES6 Syntax */var objects = data.filter(str => str !== "").map(function (str) {
var [UserId, Type, Values] = str.split(" ");
return { UserId, Type, Values };
});
/* ES5 Syntax */var objectsES5 = data.filter(function (str) {
return str !== "";
}).map(function (str) {
var split = str.split(" ");
return {
UserId: split[0],
Type: split[1],
Values: split[2]
};
});
console.log(objects);
Solution 3:
Use a combo of reduce
and split
:
var strings = [
"A123 G 2323232",
"F345 G 345667",
"T677 G -34343",
"G454 G 4343",
""
];
var result = strings.reduce(function(res, str) { // for each string in strings arraysvar parts = str.split("\t"); // split the string by tabsif(parts.length === 3) { // if the string is valid (the splitting yielded 3 parts)
res.push({ // then add an object to the result array using the parts we gotUserID: parts[0],
Type: parts[1],
Values: parts[2]
});
}
return res;
}, []);
console.log(result);
Solution 4:
You can do it using javascript filter()
and map()
methods like following.
var array = ["A123 G 2323232",
"F345 G 345667",
"T677 G -34343",
"G454 G 4343",
""];
var result = array.filter(function(item) {
return item.trim();
}).map(function(item) {
var split = item.split(' ');
return {
UserId: split[0],
Type: split[1],
Values: split[2]
};
});
console.log(result);
Post a Comment for "Transform String Of Objects Into Elements Of Object"