Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting string array into a key value pair object

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

like image 954
soum Avatar asked Dec 10 '14 22:12

soum


People also ask

How do you convert an object to a key value pair?

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.

Is array key value pair?

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.


3 Answers

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();
}
like image 52
Barmar Avatar answered Nov 14 '22 20:11

Barmar


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]
    }
like image 39
Yehia Awad Avatar answered Nov 14 '22 20:11

Yehia Awad


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)
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
  • http://www.ecma-international.org/ecma-262/6.0/#sec-object-initializer
like image 20
David Wickström Avatar answered Nov 14 '22 21:11

David Wickström