Check if object key exists within object

后端 未结 7 1796
终归单人心
终归单人心 2020-12-31 04:16

I\'m trying to take some data from an existing object and group it into a new one. The problem I am having is checking if the object key exists so I can either create a new

7条回答
  •  一整个雨季
    2020-12-31 05:00

    The best way to achieve this would be to rely on the fact that the in operator returns a boolean value that indicates if the key is present in the object.

    var o = {k: 0};
    
    console.log('k' in o); //true
    

    But this isin't your only issue, you do not have any lookup object that allows you to check if the key is already present or not. Instead of using an array, use a plain object.

    var groups = {};
    

    Then instead of groups.push(...), do groups[group_key] = group_details;

    Then you can check if the group exist by doing if (group_key in groups) {}

提交回复
热议问题