2016-10-15 8 views
0

それが戻っているkey0であるならば、私が得る価値がundefined戻る数値ゼロ

var obj = {'some','values'}; 

function getObjectKey(){ 

    obj.forEach(function(value, key) { 
     if(some condition){ 
     return key; 
     } 
    }); 

} 

var objectKey = getObjectKey(); 
console.log(objectKey); //returns `undefined` if the key returned is 0. 

どのようにされ、いくつかの条件に基づいてobjectkeyを返しfunctionがありますキーが0の場合はキーを取得しますか?

+0

有効なオブジェクトにobjを変更してください。書かれているように、間違った括弧で配列することもできます。 –

+0

[JavaScriptオブジェクトはキー用の文字列を使用する](https://stackoverflow.com/documentation/javascript/188/objects#t=201610151230320519827&a=remarks) – transistor09

+0

@downvoter:私はdownvoteの理由を知ることができますか? – Abhinav

答えて

1

Array#forEachにはループを終了させるための短絡回路がないので、別の方法が必要です。

この場合は、より良いArray#someを使用してください。配列の要素が与えられたテストを満たす場合

function getObjectKey(object, condition){ 
 
    var k; 
 

 
    Object.keys(object).some(function(key) { 
 
     if (condition(object[key])) { 
 
      k = key; 
 
      return true; 
 
     } 
 
    }); 
 
    return k; 
 
} 
 

 
var object = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5 }; 
 

 
console.log(getObjectKey(object, function (v) { return v === 3; }));

ES6を使用すると、find()方法は、アレイ内を返しArray#find

使用することができ関数。それ以外の場合はundefinedが返されます。

function getObjectKey(object, condition) { 
 
    return Object.keys(object).find(function(key) { 
 
     return condition(object[key]); 
 
    }); 
 
} 
 

 
var object = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5 }; 
 

 
console.log(getObjectKey(object, v => v === 3));

+1

配列ではなくオブジェクトで、動作するのですか? – Abhinav

+0

これはオブジェクトで動作します。 –

+1

...ありがとうございました – Abhinav

0

あなたは、オブジェクトのキーを指定する必要があります。

これは有効な構文ではありません。

[ 'some','values' ]; 

しかし、あなたが本当にオブジェクトをしたいので、キーに入れ:

{ "key0": "some", "key1": "values" }; 
0

これは配列になり

{'some','values'}; 

// there was a syntax error with your obj 
 
var obj = { 
 
    'some': 'values', 
 
    'another': 'anotherValue', 
 
    'zero': 0, 
 
    'null': null 
 
} 
 

 
// you should take the object and the key with the function 
 
function getObjectKey(obj, key){ 
 
    var keys = Object.keys(obj) 
 
    var index = keys.indexOf(key) 
 
    // if the bitshifted index is truthy return the key else return undefined 
 
    return ~index 
 
    ? obj[keys[index]] 
 
    : void 0 // void value - will change the value given to it to undefined 
 
} 
 

 

 
console.log(getObjectKey(obj, 'some')) 
 
console.log(getObjectKey(obj, 'another')) 
 
console.log(getObjectKey(obj, 'doesntExist')) 
 
console.log(getObjectKey(obj, 'zero')) 
 
console.log(getObjectKey(obj, 'null'))