[英]How can i convert this AJAX json result (which has a key/value property) into a javascript array
Given the following json result, how can I convert the validationErrors
key/value property into a nice array object in javascript so i can then do things like 给定以下json结果,我该如何在Javascript中将validationErrors
键/值属性转换为一个不错的数组对象,以便随后执行类似的操作
errors[0].Key
or 要么
errors[0].Value
, etc... errors[0].Value
等。
NOTE: If it's easier to do the conversion with jQuery, then I'm happy to use that. 注意:如果使用jQuery进行转换更容易,那么我很乐意使用它。 Also, I'm getting the data via jQuery -> $.post
...) 另外,我正在通过jQuery-> $.post
...获取数据。
update: 更新:
Here's the actual json data so someone can answer this with JSFiddle please. 这是实际的json数据,因此有人可以通过JSFiddle进行回答。
{
"aaaa": 0,
"bbbb": 0,
"cccc": null,
"validationErrors": {
"a1_7127763-1c7ac823-61d5-483f-a9ca-4947e9eb8145": "Invalid PropertyType. Please choose any property except Unknown.",
"a2_7127763-1c7ac823-61d5-483f-a9ca-4947e9eb8145": "A State is required. Eg. Victoria or New South Wales.",
"b1_5433417-18b5568a-d18e-45e2-9c63-30796995e2d3": "Invalid PropertyType. Please choose any property except Unknown.",
"b2_5433417-18b5568a-d18e-45e2-9c63-30796995e2d3": "A State is required. Eg. Victoria or New South Wales.",
"c1_6655305-297c57f9-a460-4101-be7d-70c6b9a565d5": "Invalid PropertyType. Please choose any property except Unknown.",
"c2_6655305-297c57f9-a460-4101-be7d-70c6b9a565d5": "A State is required. Eg. Victoria or New South Wales."
}
}
I would take all the keys of the object and then map them to an array. 我将使用对象的所有键,然后将它们映射到数组。
var arrayOfErrors = Object.keys(objectOfErrors).map(function(errorKey) {
return objectOfErrors[errorKey];
});
You can use map
to convert the object to an array: 您可以使用map
将对象转换为数组:
var errors = jQuery.map(data.validationErrors, function (value, key) {
return {
"Key": key,
"Value": value
};
});
JSFiddle showing this approach: http://jsfiddle.net/WgaFb/1/ JSFiddle展示了这种方法: http : //jsfiddle.net/WgaFb/1/
If you do not wish to use jQuery, here is a pure JavaScript method: 如果您不想使用jQuery,请使用以下纯JavaScript方法:
var errors = [];
for(var key in data.validationErrors) {
errors.push({
"Key": key,
"Value": data.validationErrors[key]
});
}
JSFiddle for this second approach: http://jsfiddle.net/4WXEF/1/ JSFiddle用于第二种方法: http : //jsfiddle.net/4WXEF/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.