我需要将此json对象转换为json数组

时间:2015-05-26 08:08:10

标签: javascript json

我需要转换这个json对象:

"errors": {
    "store_id": [
        "The storeid field is required."
    ],
    "first_name": [
        "The firstnamefieldisrequired."
    ],
    "last_name": [
        "The lastnamefieldisrequired."
    ],
    "email": [
        "The emailfieldisrequired."
    ],
    "password": [
        "The passwordfieldisrequired."
    ]
}

进入javaScript数组。该数组应包含类似&#34的错误; storeid字段是必需的。"," firstnamefieldisrequired。"

2 个答案:

答案 0 :(得分:0)

var o = {
    "store_id": [
        "The storeidfieldisrequired."
    ],
    "first_name": [
        "The firstnamefieldisrequired."
    ],
    "last_name": [
        "The lastnamefieldisrequired."
    ],
    "email": [
        "The emailfieldisrequired."
    ],
    "password": [
        "The passwordfieldisrequired."
    ]
}
var a = [];
var keys = Object.keys(o);
var length = keys.length;
for (var i = 0; i < length; i++) {
  a.push(o[keys[i]]);
}

答案 1 :(得分:0)

Object.keysArray.prototype.map在这里特别有帮助。

function objectToArray(obj) {
  return Object.keys(obj)
  .map(function(key) {
    return obj[key];
  });
}

这会将您的对象转换为平面数组,并在键和元素之间进行一对一映射。

{ a: 1, b: 2, c: 3 } -> [1, 2, 3]

但是,你的数组是二维的。每个键都有一个数组作为属性。像这样:

{ a: [1], b: [2], c: [3] } -> [[1], [2], [3]]

因此,您必须在转换结束时添加连接步骤。

function flatten(errors) {
  return errors.reduce(function(errorList, errors) {
    return errorList.concat(errors);
  }, []);
}

这使用Array.prototype.reduce来连接每个数组,以提供二维数组的扁平形式。

最终结果:

var json = {
    "store_id": [
        "The storeid field is required."
    ],
    "first_name": [
        "The firstnamefieldisrequired."
    ],
    "last_name": [
        "The lastnamefieldisrequired."
    ],
    "email": [
        "The emailfieldisrequired."
    ],
    "password": [
        "The passwordfieldisrequired."
    ]
};

var errorList = flatten(objectToArray(json));