将对象转换为json?

时间:2017-08-31 11:36:59

标签: javascript arrays json

我应该如何转换成这种格式

    {"Campaign Technical Approach Plan": "PM",  
  "Campaign Monitoring": "India",   
  "Email HTML Build": "India",  
  "Email Quality Assurance": "India"}

来自这种格式

    [[Campaign Technical Approach Plan,__PM__LOCATION__],   
  [Campaign Monitoring,India],  
  [Email HTML Build,India], 
  [Email Quality Assurance,India]]

4 个答案:

答案 0 :(得分:2)

您可以使用Array.prototype.reduce将数据数组转换为对象。然后使用JSON.stringify()

let data =  [
	['Campaign Technical Approach Plan','__PM__LOCATION__'],   
  	['Campaign Monitoring','India'],  
  	['Email HTML Build','India'], 
  	['Email Quality Assurance','India']
];


let result = JSON.stringify(data.reduce((resultObj, [ key, value ]) => { 
	resultObj[key] = value
	return resultObj;
}, {}));

console.log(result);

答案 1 :(得分:1)

您可以使用Array.prototype.reduce()

代码:



const arr = [['Campaign Technical Approach Plan', '__PM__LOCATION__'],['Campaign Monitoring', 'India'],['Email HTML Build', 'India'],['Email Quality Assurance', 'India']];
const result = arr.reduce(function (a, c) {
  a[c[0]] = c[1].replace(/_|LOCATION/g, '');
  return a; 
}, {});

console.log(result);




答案 2 :(得分:0)

这很直截了当。只需遍历列表即可构建您的对象。

var input = [["Campaign Technical Approach Plan","__PM__LOCATION__"],   
  ["Campaign Monitoring","India"],  
  ["Email HTML Build","India"], 
  ["Email Quality Assurance","India"]];

var obj = {};

input.forEach(function(item){
  obj[item[0]] = item[1].replace(/_|LOCATION/g, "");
});

console.log(obj);

答案 3 :(得分:-1)

简单。

var object =  {"Campaign Technical Approach Plan": "PM",  
  "Campaign Monitoring": "India",   
  "Email HTML Build": "India",  
  "Email Quality Assurance": "India"}

var JSON = JSON.stringify(object); //Converted to JSON 

相反(JSON到JS对象)使用JSON.parse()