I am getting an output which looks like this
var x = ["title: x_one", " description: 1", " value: 4"]
where x[0]
returns title: x_one
Which is a string. I cant read the property of title. How would I convert it into an object so that eventually I will be able to loop through the array and read the properties such as title, description and value.
I am trying to do this through jquery
I have been looking for a solution but havent really found one. If there is any out there which I am missing I would highly appreciate if anyone else have and could point me to that
To convert a JavaScript object into a key-value object array, we can use the Object. entries method to return an array with of key-value pair arrays of a given object. Then we can use the JavaScript array map method to map the key-value pair arrays into objects.
Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well. Simple Array eg. We see above that we can loop a numerical array using the jQuery.
Loop through your array, splitting the values at the :
character. Then use the first part as a property name, the second part as the value, in an object.
var obj = {};
for (var i = 0; i < x.length; i++) {
var split = x[i].split(':');
obj[split[0].trim()] = split[1].trim();
}
Try this function I have already tested it
var a=new Array();
for(var i=0;i<x.length;i++){
var tmp=x[i].split(":")
a[tmp[0]]=tmp[1]
}
A more up to date version that that uses some newer language
const splitStr = (x) => {
const y = x.split(':');
return {[y[0].trim()]: y[1].trim()};
}
const objects = ["title: x_one", " description: 1", " value: 4"].map(splitStr)
console.log(objects)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With