Reputation: 443
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 "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.
Upvotes: 0
Views: 95
Reputation: 11116
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);
Upvotes: 3
Reputation: 386550
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; }
Upvotes: 3
Reputation: 20740
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);
Upvotes: 1
Reputation: 31682
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 arrays
var parts = str.split("\t"); // split the string by tabs
if(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 got
UserID: parts[0],
Type: parts[1],
Values: parts[2]
});
}
return res;
}, []);
console.log(result);
Upvotes: 1