Skip to content
Advertisement

Javascript Split String in Array to Objects in Array

I have this Array ["2.900000F02A_1313_01","2.600000F02A_1315_03","2.900000F02A_1354_01"]

And I want to split it like this:

[
    {"name":"F02A_1313_01", "Voltage":"2.900000"}, 
    {"name":"F02A_1315_03", "Voltage":"2.600000"},
    {"name":"F02A_1354_01", "Voltage":"2.900000"}
]

This is my Code that doesn’t work:

for (var i in msg.strg) {
     array.push(i.split(/[a-zA-Z].*/g));
 }

Does somebody know how I can do this?

Advertisement

Answer

You could split with a group.

const
    data = ["2.900000F02A_1313_01", "2.600000F02A_1315_03", "2.900000F02A_1354_01"],
    result = data.map(string => {
        const [Voltage, name] = string.split(/([a-z].*$)/i);
        return { name, Voltage };
    });

console.log(result);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement