获取嵌套对象/数组JavaScript的值

Liz*_*ody 1 javascript arrays object

如何获取此嵌套对象的数组中的所有值:

{
    "report": {
        "firstSection": {
            "totalIncome": 9650000,
            "category": null,
            "mustPay": null,
            "tax": null,
            "bef": null,
            "message": "Los ingresos exceden el monto máximo para la modalidad monotributo"
        },
        "secondSection": {
            "subTotals": {
                "intTotal": 6295.166666666666,
                "ordTotal": 3884679.201041667
            },
            "unitaryProductionCost": 247.55291005291008,
            "unitaryInfo": {
                "unitarySalesCost": 16338.425925925927,
                "unitarySalesPrice": 23536.585365853658
            },
            "bankDebts": 0,
            "monthlySimpleDepreciation": 173333.33333333334
        },
    }
};
Run Code Online (Sandbox Code Playgroud)

基本上我想要一个像这样的数组,只有值:

{
    "report": [
        9650000,
        null,
        null,
        null,
        null,
        "Los ingresos exceden el monto máximo para la modalidad monotributo",
        6295.166666666666,
        3884679.201041667,
        247.55291005291008,
        16338.425925925927,
        23536.585365853658,
        0,
        173333.33333333334,
    ]
}
Run Code Online (Sandbox Code Playgroud)

我有这个repl.it如果有帮助https://repl.it/@lizparody/UnlinedCruelResearch谢谢!

Ori*_*ori 7

这种递归方法Object.values()用于获取当前对象的值.使用迭代值Array.reduce().如果值是一个对象(而不是null),那么它也会使用该方法进行迭代.实际值组合成一个数组Array.concat():

const obj = {"report":{"firstSection":{"totalIncome":9650000,"category":null,"mustPay":null,"tax":null,"bef":null,"message":"Los ingresos exceden el monto máximo para la modalidad monotributo"},"secondSection":{"subTotals":{"intTotal":6295.166666666666,"ordTotal":3884679.201041667},"unitaryProductionCost":247.55291005291008,"unitaryInfo":{"unitarySalesCost":16338.425925925927,"unitarySalesPrice":23536.585365853658},"bankDebts":0,"monthlySimpleDepreciation":173333.33333333334}}};

const getObjectValues = (obj) => 
  Object.values(obj).reduce((r, v) => 
    r.concat(v && typeof v === 'object' ? getObjectValues(v) : v)
  , []);
  
const result = getObjectValues(obj);

console.log(result);
Run Code Online (Sandbox Code Playgroud)