Javascript 如何检查JSON密钥';如果不使用';我不知道钥匙

Javascript 如何检查JSON密钥';如果不使用';我不知道钥匙,javascript,arrays,json,Javascript,Arrays,Json,如果不知道JSON键的名称,如何检查该键值中的值是否为数组? 我可能会收到两种不同格式的JSON对象: { "person": [{ "id": "1", "x": "abc", "attributes": ["something"] }, { "id": "1", "x": "abc" } ] } 根据格式

如果不知道JSON键的名称,如何检查该键值中的值是否为数组? 我可能会收到两种不同格式的JSON对象:

 {
    "person": [{
            "id": "1",
            "x": "abc",
            "attributes": ["something"]
        },
        {
            "id": "1",
            "x": "abc"
        }
    ]
 }
根据格式的不同,我将对其进行不同的解析。我的目标是创建一个if语句来检测键的值是数组还是仅仅是一个值,而不知道键的名称(在上面的代码中,假设我不知道“attributes”的名称)。我如何做到这一点?我不仅要遍历所有person对象,还要遍历它的所有键

我找到了一个解决方案,知道属性的名称,只有一个对象“person”,但不知道如何在多个“person”对象的基础上构建,而不知道键的名称

if (Array.isArray(json.person['attributes'])) // assuming I hold the JSON in json var and I parse it with JSON.parse
    {

    } 

您可以尝试以下方法:

数据有效载荷:

const payload =  {
    person: [
        {
            id: 1,
            x: 'abc',
            attributes: ['something']
        },
        {
            id: 1,
            x: 'abc'
        }
    ]
};
函数,如果某个条目的值为数组,则该函数将返回:

const arrayEntries = json => {

    let response = [{
        isArray: false,
        jsonKey: null,
        jsonValue: null
    }];

    Object.entries(json).map(entry => {
        if (Array.isArray(entry[1])) {
            response.push({
                isArray: true,
                jsonKey: entry[0],
                jsonValue: entry[1]
            });
        }
    });

    return response;
}
用法示例:

payload.person.map(person => {
    console.log(arrayEntries(person));
});
返回的内容如下:

代码笔链接:


ES5版本:

function arrayEntries(json) {

    var response = [{
        isArray: false,
        jsonKey: null,
        jsonValue: null
    }];

    Object.entries(json).map(function(entry) {
        if (Array.isArray(entry[1])) {
            response.push({
                isArray: true,
                jsonKey: entry[0],
                jsonValue: entry[1]
            });
        }
    });

    return response;
}

payload.person.map(function(person) {
    console.log(arrayEntries(person));
});

是否有超过这3把钥匙?如果您只有3个键,则可以使用
rest
进行解构<代码>常量{id,x,…rest}=personObject;console.log(Object.values(rest)[0])这听起来像是Object.values()应该解决的问题。是的,假设我们还不知道person对象中的键数。它可能是3,也可能是300。如果您有300个属性,您要检查数组的哪个确切属性?如果其中任何一个是数组?如果所有的属性都是数组?所有的属性,我都需要遍历它们。有没有可能用标准(非箭头)语法编写?在服务器上的控制台上,它似乎不起作用:(当然,这里有一个ES5版本。请检查我的答案更新。