[英]How to convert JSON object to JavaScript array?
I need to convert JSON object string to a JavaScript array.我需要将 JSON 对象字符串转换为 JavaScript 数组。
This my JSON object:这是我的 JSON 对象:
{"2013-01-21":1,"2013-01-22":7}
And I want to have:我想拥有:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['2013-01-21', 1],
['2013-01-22', 7]
]);
How can I achieve this?我怎样才能做到这一点?
var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [];
for(var i in json_data)
result.push([i, json_data [i]]);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(result);
If you have a well-formed JSON string, you should be able to do如果你有一个格式良好的 JSON 字符串,你应该能够做到
var as = JSON.parse(jstring);
I do this all the time when transfering arrays through AJAX.我在通过 AJAX 传输数组时一直这样做。
Suppose you have:假设你有:
var j = {0: "1", 1: "2", 2: "3", 3: "4"};
You could get the values with (supported in practically all browser versions):您可以通过以下方式获取值(几乎所有浏览器版本都支持):
Object.keys(j).map(function(_) { return j[_]; })
or simply:或者干脆:
Object.values(j)
Output:输出:
["1", "2", "3", "4"]
function json2array(json){
var result = [];
var keys = Object.keys(json);
keys.forEach(function(key){
result.push(json[key]);
});
return result;
}
See this complete explanation: http://book.mixu.net/node/ch5.html看到这个完整的解释: http : //book.mixu.net/node/ch5.html
This will solve the problem:这将解决问题:
const json_data = {"2013-01-21":1,"2013-01-22":7};
const arr = Object.keys(json_data).map((key) => [key, json_data[key]]);
console.log(arr);
Or using Object.entries() method:或者使用Object.entries()方法:
console.log(Object.entries(json_data));
In both the cases, output will be:在这两种情况下,输出将是:
/* output:
[['2013-01-21', 1], ['2013-01-22', 7]]
*/
You can insert object items to an array as this您可以像这样将对象项插入到数组中
let obj = { '1st': { name: 'stackoverflow' }, '2nd': { name: 'stackexchange' } }; let wholeArray = Object.keys(obj).map(key => obj[key]); console.log(wholeArray);
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
Consider having a json object we want to convert考虑有一个我们想要转换的 json 对象
const my_object = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
There is several solution you can use :您可以使用多种解决方案:
1. Object.keys() and Object.values() 1. Object.keys()和Object.values()
Theses functions convert any object to an array.这些函数将任何对象转换为数组。 One returns an array with all the keys, and the other all the values :
一个返回一个包含所有键的数组,另一个返回所有值:
console.log(Object.keys(my_object))
// Output : ["key1", "key2", "key3"]
console.log(Object.values(my_object))
// Output : ["value1", "value2", "value3"]
I'm not sure to understand the initial question, but the solution would probably be我不确定是否理解最初的问题,但解决方案可能是
data.addRows(Object.values(my_object));
2. Object.entries() 2. Object.entries()
This function is a mix of the two above:这个函数是上面两个的混合:
console.log(Object.entries(my_object))
// Output : [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]]
It no use for the initial question, but this function is so usefull I had to mention it.它对最初的问题没有用,但是这个功能非常有用,我不得不提一下。 Especially, when the value_ are nested object.
特别是当value_是嵌套对象时。 Let say our values are objects like this :
假设我们的值是这样的对象:
const my_object = {
"key1": {"a": 1, "b": 2},
"key2": {"y": 25, "z": 26},
"key3": {"much": "stuff"}
}
and we want to end up with an array like this我们希望以这样的数组结束
my_array = [
{"key": "key1", "a": 1, "b": 2},
{"key": "key2", "y": 25, "z": 26},
{"key": "key3", "much": "stuff"}
]
We need to use Object.entries()
to get all our key with their value.我们需要使用
Object.entries()
来获取我们所有的键及其值。 We will start with an overdetailed code :我们将从一个过于详细的代码开始:
my_array = Object.entries(my_object).map(function(entry){
key = entry[0];
value = entry[1];
nested_object = value;
nested_object.key = key;
return nested_object;
});
console.log(my_array);
// Expected output : [
// {"key": "key1", "a": 1, "b": 2},
// {"key": "key2", "y": 25, "z": 26},
// {"key": "key3", "much": "stuff"}
//]
We can make use of spread operator to simplify our code :我们可以利用扩展运算符来简化我们的代码:
my_array = Object.entries(my_object).map(entry => {"key": entry[0], ...entry[1]});
console.log(my_array);
// Expected output : [
// {"key": "key1", "a": 1, "b": 2},
// {"key": "key2", "y": 25, "z": 26},
// {"key": "key3", "much": "stuff"}
//]
Some correction to @Mister Aqua's SOLUTION对@Mister Aqua 的解决方案的一些更正
const my_array = [];
Object.entries(set_of_objects).map(function (entry) {
const key = entry[0];
const value = entry[1];
const nested_object = {};
nested_object[key] = value;
my_array.push(nested_object);
});
Chill Pill :)清凉丸 :)
if the goal is to create an array of objects, here is a solution that will accomplish what you're trying to do using Object.keys() and Object.values():如果目标是创建一个对象数组,这里有一个解决方案,可以使用 Object.keys() 和 Object.values() 完成您尝试做的事情:
const jsonResponse = '{"2013-01-21":1,"2013-01-22":7}'
// Only use json parse if the data is a JSON string.
const obj = typeof jsonResponse === 'string' ? JSON.parse(jsonResponse) : jsonResponse;
const data = [];
Object.keys(obj).forEach((key, i) => data.push({[key]: Object.values(obj)[i]}))
Or using Object.entries()或使用 Object.entries()
Object.entries(obj).forEach((array, index) => data.push({[array[0]]: array[1]}))
As simple as this !就这么简单!
var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.