I have received result from Raspberry Pi as Text format and I want to use these text to insert into MongoDB as key-pair value or JSON for my Node.js Application. However, I am quite new with JavaScript and trying to figure out the solution. Please help me if you have any suggestion, Thank you very much.
Example:
//Text from Raspberry Pi
1, 2300,450
2, 2200, 920
3, 3400, 440
and I want it to be
[
{
person: 1,
x position: 2300,
y position: 450
},
{
person: 2,
x position: 2200,
y position: 920
},
{
person: 3,
x position: 3400,
y position: 440
}
]
5
Answers
Use split and map
You can transform your string into an array, use an array to store the exact name of your keys and then through .reduce create your new array.
You can first create array from the text by using
split
method and then convert the input array to the array of the object/n
to get the lines,
to get all the elementsCode snippet
Try here
My own suggestion would be:
JS Fiddle demo.
This, of course, relies upon the result being returned from the Pi with each entry on a new line; if this can’t be guaranteed, or the Pi returns entries in a String without new-lines, the following may be preferred:
JS Fiddle demo.
References:
[...]
.Array.prototype.map()
.Array.prototype.reduce()
.document.querySelector()
.document.querySelectorAll()
.Element.querySelector()
.Element.querySelectorAll()
.EventTarget.addEventListener()
.String.prototype.split()
.