Javascript 检查对象数组是否包含某个键
我需要确定对象数组中是否存在某个键 以下是一个示例阵列:Javascript 检查对象数组是否包含某个键,javascript,arrays,node.js,json,object,Javascript,Arrays,Node.js,Json,Object,我需要确定对象数组中是否存在某个键 以下是一个示例阵列: arrOfObj = [{ "mainKey1": { "subKey1": { "innerKey1": { "innerMostKey1": { "key1": "value" } }
arrOfObj = [{
"mainKey1": {
"subKey1": {
"innerKey1": {
"innerMostKey1": {
"key1": "value"
}
}
}
}
}, {
"mainKey2": {
"key2": "value"
}
}, {
"mainKey3": {
"subKey3": {
"key3": "value"
}
}
}
]
我试图这样做,但我得到了错误的输出:
const objKeys = Object.keys(arrOfObj)
console.log('objKeys = ' + JSON.stringify(arrOfObj))
输出为索引编号:
objKeys = ["0", "1", "2"]
我希望有一个这样的函数:
var isKeyPresent = checkKeyPresenceInArray('mainKey3')
但请注意,我只需要检查对象的最顶层-在上面的示例中,这些是主键(mainKey1
,等等),它们的内容是动态的(一些其他对象内部有深度嵌套的对象,而一些则没有)
帮助!您可以尝试使用
数组。some()
:
让arrOfObj=[{
“主键1”:{
“子键1”:{
“innerKey1”:{
“innerMostKey1”:{
“键1”:“值”
}
}
}
}
}, {
“主键2”:{
“键2”:“值”
}
}, {
“主键3”:{
“子项3”:{
“键3”:“值”
}
}
}
]
让checkKeyPresenceInArray=key=>arrOfObj.some(obj=>Object.keys(obj.includes)(key));
var isKeyPresent=checkKeyPresenceInArray('mainKey3')
console.log(isKeyPresent);
您可以遍历数组,检查并查看是否有任何对象具有要查找的密钥,如果有,则返回true。如果找不到密钥,则for
循环将完成,并返回false
arrOfObj=[{
“主键1”:{
“子键1”:{
“innerKey1”:{
“innerMostKey1”:{
“键1”:“值”
}
}
}
}
}, {
“主键2”:{
“键2”:“值”
}
}, {
“主键3”:{
“子项3”:{
“键3”:“值”
}
}
}
]
函数arrayHasKey(arr,key){
用于(arr的常量对象){
if(输入obj){return true;}
}
返回false;
}
console.log(arrayHasKey(arrOfObj,“mainKey2”))
log(arrayHasKey(arrOfObj,“mainKey10”))
这将起作用,它返回布尔值:
arrOfObj.hasOwnProperty('mainKey3');
您可以将
some
与hasOwnProperty
一起使用,如下所示:
let checkKeyPresenceInArray = (key) => arrOfObj.some((o) => o.hasOwnProperty(key));
您必须使用
hasOwnProperty
方法来检查该数组中的对象中是否存在密钥-
var c = 0;
arrOfObj.forEach(e => {
if(e.hasOwnProperty("mainKey1")){
c++;
}
});
if(c > 0 && c == arrOfObj.length){
console.log("The key is found in all the objects in the array.");
}
else if(c == 0){
console.log("The key is not found in any objects in the array");
}
else{
console.log("The key is found in some objects in the array");
}
您需要找到单个对象的键,而不是完整的数组,使用某种数组方法在数组上循环,然后针对每个元素获取键并根据所需键进行测试是否要提取数组中的所有键?由于传递的是数组,而不是对象,所以得到0,1,2。即使键存在,它也会返回false,因为它会检查ks属性,而不是对象。
var c = 0;
arrOfObj.forEach(e => {
if(e.hasOwnProperty("mainKey1")){
c++;
}
});
if(c > 0 && c == arrOfObj.length){
console.log("The key is found in all the objects in the array.");
}
else if(c == 0){
console.log("The key is not found in any objects in the array");
}
else{
console.log("The key is found in some objects in the array");
}