1

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

7
  • Where/how do you create your Array ["ID:2","ID:3","ID:4"]? Is this format of any use? Commented Oct 10, 2017 at 8:45
  • Are you asking how to convert the array to JSON or are you asking how to convert the array of strings to an array of objects? Those are two distinct problems. Commented Oct 10, 2017 at 8:46
  • Try ["ID:2","ID:3","ID:4"].map(s => {let [key, val] = s.split(':'); return {[key]: +val}}) Commented Oct 10, 2017 at 8:49
  • 1
    You should really use jQuery. It's really great and does all things. Commented Oct 10, 2017 at 8:55
  • 1
    ahhh, you were being sarcastic (or ironic?) @xenteros - nice Commented Oct 10, 2017 at 9:21

3 Answers 3

3

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);

Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.