如何获取Javascript嵌套对象的所有属性值(不知道密钥)?

时间:2018-03-29 18:07:06

标签: javascript

在参考如何做到这一点时,我看了how-to-get-all-properties-values-of-a-javascript-object-without-knowing-the-key使用ES6

如果您正在扫描的对象具有子对象,而您只需要那些值的数据,那么如何进入数组呢?

示例:

var errorData = {"Message":"The request is invalid.","ModelState":{"account.Contact.PrimaryPhone":["Primary Phone is required.","'Primary Phone' should not be empty."]}}

var errors = Object.keys(errorData).map(function (key) {
      return errorData[key];
});

不起作用。

我需要一个像这样列出的数组:

The request is invalid.
Primary Phone is required.
'Primary Phone' should not be empty.

4 个答案:

答案 0 :(得分:2)

API响应通常有固定的结构,或者至少是某个指南。您可以测试值的类型,并查看它是数组还是对象。您还可以预测响应中的特定键,测试其存在,并相应地进行工作。

答案 1 :(得分:1)

最简单的方法可能是使用递归函数。你可以在现代引擎中这样做:

const errorData = {"Message":"The request is invalid.","ModelState":{"account.Contact.PrimaryPhone":["Primary Phone is required.","'Primary Phone' should not be empty."]}}

const errors = (function flattenValues( obj ) {
  return Object.values( obj ).reduce(
    ( values, value ) => values.concat( typeof value === "object" ? flattenValues( value ) : value )
  , [ ] );
} )( errorData );

console.log( errors );

虽然Object.values只有最近的浏览器支持,所以你可能想要使用具有更多兼容性的东西:

var errorData = {"Message":"The request is invalid.","ModelState":{"account.Contact.PrimaryPhone":["Primary Phone is required.","'Primary Phone' should not be empty."]}}

var errors = (function flattenValues( obj ) {
  return Object.keys( obj ).reduce( function ( keys, key ) {
    var value = obj[key];
    return values.concat( typeof value === "object" ? flattenValues( value ) : value );
  }, [ ] );
} )( errorData );

console.log( errors );

答案 2 :(得分:0)

这应该有效。只是通过它,没有完全测试它。

Object.values(a)
  .map(v => v instanceof Object ? Object.values(v) : [v])
  .reduce((acc, next) => acc.concat(...next), [])

答案 3 :(得分:0)

let errorData = {"Message":"The request is invalid.","ModelState":{"account.Contact.PrimaryPhone":["Primary Phone is required.","'Primary Phone' should not be empty."]}}

const flatten = (obj) => obj.reduce((acc, val) => acc.concat(val), []);

const unwrap = (obj) => 
    Object.keys(obj).map((key) => { 
        if (typeof(obj[key]) == 'object') 
            return flatten(unwrap(obj[key]));
        else
            return obj[key];
    });

let errors = flatten(unwrap(errorData));