json 检查对象内是否存在对象键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18922965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if object key exists within object
提问by KenTenMen
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.
我发现了一些类似的问题,但没有一个答案有效,所以我有点卡住了。它总是最终发现它不存在并创建重复的键。
I have the following code, where xxxis where I need to check if the key exists:
我有以下代码,xxx我需要在哪里检查密钥是否存在:
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
});
}
}
The somethingI am passing in, is pretty simple, basically in the form of:
在something我传递的,是非常简单的,基本的形式:
[
{
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'
}
]
回答by plalx
The best way to achieve this would be to rely on the fact that the inoperator returns a boolean value that indicates if the key is present in the object.
实现这一点的最佳方法是依赖于in运算符返回一个布尔值来指示键是否存在于对象中这一事实。
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;
然后,而不是groups.push(...),做groups[group_key] = group_details;
Then you can check if the group exist by doing if (group_key in groups) {}
然后您可以通过执行检查该组是否存在 if (group_key in groups) {}
回答by Tore Hanssen
I have run into this pattern a lot, and what I end up doing is:
我经常遇到这种模式,我最终做的是:
if (object[key]) {
//exists
} else {
// Does not exist
}
so I think in your case it will be:
所以我认为在你的情况下它将是:
if (groups[group_key]) {
// Exists
} else {
// Does not exist
}
回答by Bruno Oliveira
let data = {key: 'John'};
console.log( data.hasOwnProperty('key') );
回答by Kaibo
You should use the inoperator
您应该使用in运算符
key in object //true
!(key in object) //false
And undefinedcan not be used
并且undefined不能使用
obj["key"] !== undefined //false, but the key in the object
For more information, please look at Checking if a key exists in a JavaScript object?
有关更多信息,请查看检查 JavaScript 对象中是否存在键?
回答by Faton
You can use hasOwnProperty() function.
您可以使用 hasOwnProperty() 函数。
var groups = [];
for (var i=0; i<something.length; i++) {
var group_key = 'group_'+something[i].group_id;
if (!groups.hasOwnProperty(group_key)) {
// New group
var group_details = {};
group_details[group_key] = {//maybe change to group_details =
group_name: something[i].group_name,
items: [
{ 'name': something[i].name }
]
};
//groups.push(group_details);
//change it to
groups[group_key] = group_details;
} else {
// Existing group
groups[group_key].items.push({
'name': something[i].name
});
}
}
回答by Nishad K Ahamed
you could retrieve keys from object and iterate through the list and see if the key is exist or not:
您可以从对象中检索键并遍历列表并查看键是否存在:
var keys=Object.keys(object)
for(var i=0;i<keys.length;i++){
if(keys[i]=="your key"){//check your key here}
}
回答by scorp1984
ExampleArray
示例数组
[0] => siteoverlay
[1] => overlaycenter
[2] => someelementid
Solution A
方案一
extend prototype if you want,(function here with while loop which is much faster than for in):
如果需要,请扩展原型,(在这里使用 while 循环比 for in 快得多):
if (!('getKey' in Object.prototype)) {
Object.prototype.getKey = function(obj) {
var i=this.length;
while(i--)
{ if(this[i]===obj)
{return i;}
return;
}
};
}
then you can use:
那么你可以使用:
alert(exampleArray.getKey("overlaycenter"));
returns: 1
回报:1
Solution B
方案B
also with prototype extension:
还带有原型扩展:
if(!('array_flip' in Array.prototype)){
Array.prototype.array_flip=function(array) {
tmp_ar={}; var i = this.length;
while(i--)
{ if ( this.hasOwnProperty( i ) )
{ tmp_ar[this[i]]=i; }
} return tmp_ar;
};
}
and then you can use:
然后你可以使用:
alert(exampleArray.array_flip(exampleArray['someelementid']);
returns: 2
回报:2
Solution C
方案C
found out without prototype addition it is also functional
发现没有原型添加它也是功能性的
and eventually better for compatible scripting as everyone says not to extend the prototype...and so,...yes, if you want to use it with an easy 1 liner then you can use:
并最终更好地兼容脚本,因为每个人都说不要扩展原型......所以,......是的,如果你想用一个简单的 1 衬垫使用它,那么你可以使用:
function array_flip( array )
{ tmp_ar={}; var i = array.length;
while(i--)
{ if ( array.hasOwnProperty( i ) )
{ tmp_ar[array[i]]=i; }
} return tmp_ar;
}
And
和
alert(array_flip(exampleArray)['siteoverlay']);
returns 0
返回 0

