在JSON对象中查找属性

时间:2012-04-06 18:31:40

标签: javascript jquery json

我正在创建一个像

这样的JSON对象
tags = {"jon":["beef","pork"],"jane":["chicken","lamb"]};

是使用像

这样的数组中的php生成的
$arr = array(
        'jon' => array('beef', 'pork'),
        'jane' => array('chicken', 'lamb')
       );
$tags = json_encode($arr);

我想检查一下是否存在某种情况。这些似乎都不起作用,但类似

if('lamb' in tags.jane)) {
    console.log('YES');
} else {
    console.log('NO');
}

NO 写入控制台

if('foo' in tags.jane)) {
    console.log('YES');
} else {
    console.log('NO');
}

还将 NO 写入控制台

所以看着

typeof(tags.jane);

它显示它是"object"

console.log(tags);

显示以下内容:

Object
jane: Array[2]
    0: "chicken"
    1: "lamb"
    length: 2
    __proto__: Array[0]
jon: Array[2]
    0: "beef"
    1: "pork"
    length: 2
    __proto__: Array[0]
__proto__: Object

所以我想也许tags.jane实际上可能是一个数组并尝试了

if($.inArray('lamb', tags.jane)) {
    console.log('YES');
} else {
    console.log('NO');
}

YES 写入控制台,但

if($.inArray('foo', tags.jane)) {
    console.log('YES');
} else {
    console.log('NO');
}

还会将 YES 写入控制台。

我是否错误地构建了JSON对象?没有正确定位价值?任何意见是极大的赞赏。如果这更容易作为数组而不是对象,我可以完全控制它来改变它。我对如何对待这件事感到有点难过。

5 个答案:

答案 0 :(得分:4)

当找不到元素时,

jQuery.inArray返回-1。这是来自Javascript POV的true值。试试这个:

if($.inArray('foo', tags.jane) != -1) {

答案 1 :(得分:3)

你的第二套答案就是你应该去的方式。但是,$ .inArray返回索引,而不是布尔值。任何非零整数都为true,这意味着当找不到foo时,它返回-1,其值为true并打印 YES

同样,$.inArray('chicken', tags.jane)会返回0并转为false,这也不是您想要的答案。

相反,请使用$.inArray('foo', tags.jane) !== -1作为您的条件。

答案 2 :(得分:2)

tags.name将为您提供该人的数组。所以$.inArray("chicken",tags.jane)会看到“鸡”是否在jane的标签数组中。如果不是,那么你得到-1,否则你就是它在数组中的位置(使用你的例子,这将返回零,第一个数组元素)。

答案 3 :(得分:1)

您出于错误的原因使用了关键字in。 语句(prop'in'obj)检查对象(关联数组)是否具有值为prop的属性。 由于您在数组上使用'in'关键字,因此将返回false,因为tags.jane是一个包含索引的数组,而不是具有属性的关联数组。

如果你想知道数值是否在数组中,那么循环并比较。 如果要使用'in'关键字,请将数组转换为如此对象。

    tags = {};
    // old code
    tags.jane = ['lamb', 'food']; 
console.log(('lamb' in tags.jane) === false )
    // new code
    tags.jane = {
       'lamb':1,
        'food':1
    }
console.log(('lamb' in tags.jane) === true )

https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in

答案 4 :(得分:0)

你不能使用

if('foo' in tags.jane))

应该用作

if (1 in tags.jane)

如果你想在tags.jane中检查'foo',试试这个

var inIt = (function() {
    var inIt = false;
    tags.jane.forEach(function(item) {
        inIt = inIt || 'foo' == item;
    });
    return inIt;
})();