检查数组中是否存在对象键 [英] Check if object key exists within array

查看:94
本文介绍了检查数组中是否存在对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从现有对象中获取一些数据并将其分组为一个新对象.我遇到的问题是检查对象密钥是否存在,以便我可以创建一个新的密钥,也可以将数据追加到现有的密钥.

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 one, or append data to an existing one.

我发现了一些类似的问题,但是没有一个答案起作用,所以我有点卡住了.它总是最终发现它不存在并创建重复的密钥.

I've found a few similar questions but none of the answers worked so I'm a bit stuck. It always ends up finding it doesn't exist and creating duplicate keys.

我有以下代码,其中xxx是我需要检查密钥是否存在的地方:

I have the following code, where xxx is where I need to check if the key exists:

var groups = [];    

for (var i=0; i<something.length; i++) {

    var group_key = 'group_'+something[i].group_id;

    if (xxx) {

        // New group

        var group_details = {};

        group_details[group_key] = {
                group_name: something[i].group_name,
                items:  [
                    { 'name': something[i].name }
                ]
        };
        groups.push(group_details);

    } else {

        // Existing group

        groups[group_key].items.push({
            'name': something[i].name
        });

    }

}

我要传递的something非常简单,基本上是以下形式:

The something I am passing in, is pretty simple, basically in the form of:

[
    {
        group_id: 3,
        group_name: 'Group 3',
        name: 'Cat'
    },
    {
        group_id: 3,
        group_name: 'Group 3',
        name: 'Horse'
    },
    {
        group_id: 5,
        group_name: 'Group 5',
        name: 'Orange'
    }
]

推荐答案

实现此目标的最佳方法是依靠in运算符返回一个布尔值的事实,该值指示对象中是否存在键

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 = {};

然后代替groups.push(...),执行groups[group_key] = group_details;

然后您可以通过执行if (group_key in groups) {}

这篇关于检查数组中是否存在对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆