0

I've got an array that looks like this:

thing1,thing2,thing3

I need to reformat it to look like this:

[ 
{ value: 'thing1', data: 'thing1' }, 
{ value: 'thing2', data: 'thing2' }, 
{ value: 'thing3', data: 'thing3' }, 
]

My current function looks like this, but clearly isn't working:

function combine_ids(ids) {
   return (ids.length ? " [ { value: '" + ids.join("'," + " data: '" + ids + " ' } ] ")  : "");
}
2
  • Check this link: stackoverflow.com/questions/15009448/… Commented Jun 10, 2015 at 19:14
  • @MuhammadBilal, that has nothing to do with what I'm asking. Commented Jun 10, 2015 at 19:55

2 Answers 2

2

Assuming that you array looks like this

var arr = ["thing1","thing2","thing3"]

You can use .map() like this

var result = arr.map(function(item){ 
  return {"value": item, "data": item}; 
});

which will return this

[
 {"value":"thing1","data":"thing1"},
 {"value":"thing2","data":"thing2"},
 {"value":"thing3","data":"thing3"}
]

You can alter your method like this

function combine_ids(arr){
  return arr.map(function(item){ 
     return {"value": item, "data": item}; 
  });
}

var result = combine_ids(arr);

var arr = ["thing1","thing2","thing3"]
function combine_ids(arr){
  return arr.map(function(item){ 
     return {"value": item, "data": item}; 
  });
}

var result = combine_ids(arr);
alert(JSON.stringify(result));

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

Comments

0

Try this one

function combine_ids(ids) {
    var Aobj=[];
    for (var x in ids){
       Aobj.push({'value':ids[x],'data' : ids[x]})
    }
    return Aobj;
}

combine_ids(['thing1','thing2','thing3'])

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.