简体   繁体   中英

Convert a Comma Seperate Value to JSON Object in Javascript

I want to Convert a Comma Separated value of array to JSON object to formats below mentioned

INPUT

swedish,chinese,english,hindi

OUTPUT

Object {swedish: swedish, chinese: chinese, english: english,hindi: hindi}

Use Array#map over commaSeperated.split(',') returned array and return object with same key-value from the callback and wrap the array returned by .map in object having key as data

 var obj = { "data": "swedish,chinese" }; var op = obj.data.split(',').map(function(item) { var obj = {}; obj[item] = item; return obj; }); console.log({ data: op });

Edit: If expecting object as a response,

 var obj = { "data": "swedish,chinese" }; var op = { data: {} }; obj.data.split(',').forEach(function(item) { op.data[item] = item; }); console.log(op);

This will do

var temp = {"data":"swedish,chinese"}
temp.data= temp.data.split(',').reduce((res,x)=>{
  res[x] = x;
  return res
},{});
console.log(temp);

will give

{"data":{"swedish":"swedish","chinese":"chinese"}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM