如何从JSON转换为Javascript中的字符串数组?

时间:2018-08-09 03:07:54

标签: javascript arrays json

我正在使用Material-UI将mui-datatables用于ReactJS, 它要求数据是字符串数组。但是我们当前的WS返回的是JSON对象。

当前数据:

data = [{"Name":"Joe James", "Company":"Test Corp", "City":"Yonkers", "State":"NY"},
{"Name":"John Walsh", "Company":"Test Corp", "City":"Hartford", "State":"CT"}];

所需数据:

data = [["Joe James", "Test Corp", "Yonkers", "NY"],
 ["John Walsh", "Test Corp", "Hartford", "CT"]];

4 个答案:

答案 0 :(得分:5)

您可以使用Array.map和Object.values生成所需的数据

datas = [{"Name":"Joe James", "Company":"Test Corp", "City":"Yonkers", "State":"NY"},
{"Name":"John Walsh", "Company":"Test Corp", "City":"Hartford", "State":"CT"}];

const result = datas.map(Object.values);
// Or for more clear 
//  const result = datas.map(data => Object.values(data));

console.log(result)

答案 1 :(得分:1)

尝试以下操作:

data = [{"Name":"Joe James", "Company":"Test Corp", "City":"Yonkers", "State":"NY"}, 
{"Name":"John Walsh", "Company":"Test Corp", "City":"Hartford", "State":"CT"}];

result_data = [Object.values(data[0])]

答案 2 :(得分:1)

转换为javascript对象数组,然后使用Object.values()提取值

var data = data = [{"Name":"Joe James", "Company":"Test Corp", "City":"Yonkers","State":"NY"},
{"Name":"John Walsh", "Company":"Test Corp", "City":"Hartford", "State":"CT"}];

data.map(x => Object.values(x));

结果如下图所示。

enter image description here

答案 3 :(得分:-2)

看看这个

var data = '[{"Name":"Joe James", "Company":"Test Corp", "City":"Yonkers", "State":"NY"},{"Name":"John Walsh", "Company":"Test Corp", "City":"Hartford", "State":"CT"}]';

var parseData = JSON.parse(data);

var newthing = [];
for (var x in parseData) {
   newthing.push(Object.values(ph[x]));
}
console.log(newthing);