简体   繁体   中英

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

errors[0].Key

or

errors[0].Value , etc...

在此处输入图片说明

NOTE: If it's easier to do the conversion with jQuery, then I'm happy to use that. Also, I'm getting the data via jQuery -> $.post ...)

update:

Here's the actual json data so someone can answer this with JSFiddle please.

{
  "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:

var errors = jQuery.map(data.validationErrors, function (value, key) {
    return {
        "Key": key,
        "Value": value
    };
});

JSFiddle showing this approach: http://jsfiddle.net/WgaFb/1/


If you do not wish to use jQuery, here is a pure JavaScript method:

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/

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