Reputation: 123
How do I convert
["ID:2","ID:3","ID:4"]
to
[{
"ID":2
},
{
"ID":3
},
{
"ID":4
}]
because this type of data i have to send to my webservice
Upvotes: 1
Views: 84
Reputation: 5762
var aryExample = ["ID:2","ID:3","ID:4"], aryNew = [];
for( var i in aryExample ) {
aryNew.push({ID:Number(aryExample[i].split(":")[1])});
}
console.dir(aryNew);
That should do it.
Upvotes: 1
Reputation: 386786
For getting an array with objects, you could split the strings and build a new object with the wanted property and the numerical value.
var data = ["ID:2","ID:3","ID:4"],
result = data.map(function (s) {
var p = s.split(':'),
t = {};
t[p[0]] = +p[1];
return t;
});
console.log(result);
Upvotes: 3
Reputation: 1015
var newArrayOfObjs =arr.map((item)=> {
var obj = {};
var splitItems = item.split(':');
obj[splitItems[0]] = splitItems[1];
return obj;
}
You'll have to split the string on ':' and set the 0th element as key and 1st element as value.
Upvotes: 1