【问题标题】:Javascript Object get object by propertyJavascript Object 按属性获取对象
【发布时间】:2019-07-24 08:48:53
【问题描述】:

我有一个包含 2 个用户的对象,如下所示。该对象将只包含 2 个用户。

{
   "71":{
      "avatarURL":"__vue_devtool_undefined__",
      "createdAt":"2018-10-13T16:05:19Z",
      "customData":"__vue_devtool_undefined__",
      "id":"71",
      "name":"Angeline Fadel",
      "updatedAt":"2018-10-13T16:05:19Z",
      "presenceStore":{
         "71":"online"
      }
   },
   "199":{
      "avatarURL":"__vue_devtool_undefined__",
      "createdAt":"2018-10-13T16:06:13Z",
      "customData":"__vue_devtool_undefined__",
      "id":"199",
      "name":"Rodrigo Schuster",
      "updatedAt":"2018-10-13T16:06:13Z",
      "presenceStore":{
         "71":"online"
      }
   }
}

假设我的用户 ID 是 199,如何在不知道用户 ID 的情况下获取其他用户的姓名?

【问题讨论】:

  • 请不要发布图片.....而是发布代码。

标签: javascript vue.js ecmascript-6 ecmascript-5


【解决方案1】:

您可以使用Object.keys 访问这些值以获取ID。然后filter()获取其他用户

let users = {
  '71':{name:"First User"},
  '199':{name:"Second User"}
}
let id = '199'
let otherId = Object.keys(users).filter(key => key !== id)[0]
console.log(users[otherId].name);

【讨论】:

  • 但是对象中用户的顺序发生了什么变化?
  • @itsliamoco 抱歉,我想我误解了。我更新了
【解决方案2】:

var obj={
  199: {
    name: "abc"
  },
  71: {
    name: "def"
  }
}

var knownKey = 199;
var otherKey = Object.keys(obj).filter(key => key != knownKey).pop();
console.log("name = " + obj[otherKey].name);

【讨论】:

    【解决方案3】:

    使用Object.keys,您可以获得一个键数组:

    const users = { 199: {...}, 71: {...} };
    const ids = Object.keys(users); // -> ['199', '71']
    

    知道数组将只包含两项和“其他”键,您可以使用Array.prototype.find 来获取其他项:

    const myId = '199';
    const targetId = ids.find(id => id !== myId); // -> '71'
    

    请记住,对象键始终是字符串,因此您可能需要调整对 ID 的过滤和操作,使其被视为(或强制转换为)数字。

    【讨论】:

      【解决方案4】:

      您可以通过以下代码实现。假设obj 是对象,id 变量存储 id。现在,使用 Object.keys 获取键(即数组)并根据!== id 过滤掉结果。使用otherId获取相关对象和名称。

      obj = {
         "71":{
            "avatarURL":"__vue_devtool_undefined__",
            "createdAt":"2018-10-13T16:05:19Z",
            "customData":"__vue_devtool_undefined__",
            "id":"71",
            "name":"Angeline Fadel",
            "updatedAt":"2018-10-13T16:05:19Z",
            "presenceStore":{
               "71":"online"
            }
         },
         "199":{
            "avatarURL":"__vue_devtool_undefined__",
            "createdAt":"2018-10-13T16:06:13Z",
            "customData":"__vue_devtool_undefined__",
            "id":"199",
            "name":"Rodrigo Schuster",
            "updatedAt":"2018-10-13T16:06:13Z",
            "presenceStore":{
               "71":"online"
            }
         }
      }
      id = "199"
      otherId = Object.keys(obj).find(data => data !== id)
      result = obj[otherId].name
      alert(result)

      【讨论】:

      • 请注意 otherId 是一个数组:[ "71" ] 而不是 71。这可能是因为[ "71" ].toString()71。你应该改用find
      【解决方案5】:

      您可以使用 Object.keys() 获取 id 并过滤它们。

      const usrs = {
        '1': {
          name: 'a'
        },
        '2': {
          name: 'b'
        }
      };
      
      function other(usrs, id) {
        const allId = Object.keys(usrs);
        console.log('allId:', allId);
        const otherId = allId.filter(k => k !== id);
        console.log('otherId:', otherId);
        const otherUser = otherId.map(uid => usrs[uid]);
        console.log('otherUser:', otherUser);
        const otherNames = otherUser.map(u => u.name);
        return otherNames
      }
      
      console.log(other(usrs, '1'));

      【讨论】:

        【解决方案6】:

        你可以使用delete

        const users = {
           "71":{
              "avatarURL":"__vue_devtool_undefined__",
              "createdAt":"2018-10-13T16:05:19Z",
              "customData":"__vue_devtool_undefined__",
              "id":"71",
              "name":"Angeline Fadel",
              "updatedAt":"2018-10-13T16:05:19Z",
              "presenceStore":{
                 "71":"online"
              }
           },
           "199":{
              "avatarURL":"__vue_devtool_undefined__",
              "createdAt":"2018-10-13T16:06:13Z",
              "customData":"__vue_devtool_undefined__",
              "id":"199",
              "name":"Rodrigo Schuster",
              "updatedAt":"2018-10-13T16:06:13Z",
              "presenceStore":{
                 "71":"online"
              }
           }
        };
        
        const knowUserId = '199';
        const knowUserIndex = Object.keys(users).indexOf(knowUserId);
        
        if(knowUserIndex > -1){
        	delete users[knowUserId]; 
        }
        
        console.log(users)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-18
          • 2016-03-29
          • 2013-04-03
          • 1970-01-01
          • 2016-11-08
          相关资源
          最近更新 更多