使用数组中的字符串键访问JavaScript对象

Accessing JavaScript objects with string key within an array

本文关键字:访问 JavaScript 对象 字符串 数组      更新时间:2023-09-26

我有以下数据结构:

var settings = {
    notifications: [
        {
            'logout' : {
                icon: 'fa fa-sign-out',
                text: [
                    {heading: 'Logout'},
                    {body: 'You have unsaved data. Are you sure you want to log out?'},
                ]
            }
        },
        {
            'delete' : {
                icon: 'fa fa-times',
                text: [
                    {heading: 'Delete'},
                    {body: 'This operation can not be undone. Are you sure you want to delete?'},
                ]
            }
        },
    ],
};

当我不知道注销对象在通知数组中的位置时,如何检索logout.icon的值?

此处列出的纯嵌套对象的解决方案为我提供了未定义

---解决方案

根据Yassine Moustarham的回答,这里是我的可重用函数:

function getProp(arr,key,prop)
{
    for(var i=0;i<arr.length;i++)
    {
        if(arr[i][key])
        {
            return arr[i][key][prop];
        }
    }
    return false;
};
var icon = getProp(settings.notifications, 'logout', 'icon');

感谢Felix Kling的简化建议。

到此为止:如果您确定他们将明确地成为一个名为logout的通知数组元素的成员则该功能将返回他的图标成员

function getIcon()
{
    for(i=0;i<settings.notifications.length;i++)
    {
        if(typeof(settings.notifications[i].logout)!=='undefined')
        {
            return settings.notifications[i].logout.icon;
        }
    }
    return false;
}

undefined写错了!并认为Felix Kling需要在与"undefined"进行比较之前添加typeof。

您需要递归地迭代对象的属性,直到找到您要查找的密钥:

function findKey(object, key){
  if (object.hasOwnProperty(key)) {
    // do stuff
    console.log('found');
    return true;
  }
  for (var property in object) {
    if (typeof object[property]=='object') {
      return findKey(object[property], key);
    } 
  }
}
findKey({'bop':{'foo':'bar'}}, 'foo');