2017-07-17 14 views
1

を配列のインデックス値を検索:私はここ(<strong><em>stressValues</em></strong>を)この配列を持つ配列項目オブジェクトのプロパティ値に基づいて

[ { angeredoutsidecontrol: 1 }, { difficultiespileup: 2 } ] 

私は上のベースの配列のインデックス値を見つけるしたいと思います

を返しますangeredoutsidecontrolなどに含まれるオブジェクトの1のプロパティ名には、どのように私はこれを達成することができますか?

これは私がこれまで持っているものです。

for(const value of values) { 
    const stressValue = Object.values(value)[0]; 
    const valueName = Object.keys(value)[0]; 

    for (const name in stressValues) { 
    if (name === valueName) { 
     console.log(name); 
     console.log(values.indexOf(name)); // trying to get it to return 0 
    } 
    } 
} 
+1

できますが、あなたの目標を達成するために何をしたのかを示しますか? – Neal

+0

まだ何か試しましたか?また、配列に、同じプロパティ名を持つ複数のオブジェクトが含まれている場合はどうなりますか?あなたはすべての指標を返しますか? –

+0

'arr.map((e、i)=> {e.index = i; return e})' – T4rk1n

答えて

2

const arr = [ { angeredoutsidecontrol: 1 }, { difficultiespileup: 2 } ]; 
 

 

 
function checkForKey(arr, key) { 
 
    // loop through array 
 
    for(let i = 0; i < arr.length; ++i) { 
 
     const value = arr[i]; 
 
     // if value has the key, return the index 
 
     if (value.hasOwnProperty(key)) { 
 
      return i; 
 
     } 
 
    } 
 
} 
 

 

 
console.log('angeredoutsidecontrol', checkForKey(arr, 'angeredoutsidecontrol')); 
 
console.log('difficultiespileup', checkForKey(arr, 'difficultiespileup'));

+1

パーフェクト、私もかなり気になっていました。ありがとう、私はできるだけ答えとしてこれを受け入れます。 – Antoine

2

オブジェクトは常に唯一つのプロパティを持っている場合は、あなたがfindIndexObject.keysを使用することができます。

var stressValues = [ { angeredoutsidecontrol: 1 }, { difficultiespileup: 2 } ]; 
 

 
var angerIndex = stressValues.findIndex((value) => Object.keys(value)[0] === 'angeredoutsidecontrol'); 
 
console.log(angerIndex);

EDIT:あなたはより一般的な解決策が必要な場合、あなたは私たちは、そのキーに、オブジェクトが含まれるかどうかを確認指定され、includesを使用することができます。

var stressValues = [ { angeredoutsidecontrol: 1, sadness: 3 }, { difficultiespileup: 2 } ]; 
 

 
var angerIndex = stressValues.findIndex((value) => Object.keys(value).includes('angeredoutsidecontrol')); 
 
console.log(angerIndex);

+0

これは、オブジェクトごとに1つのキー/値ペアのみを使用しています_ – Neal

+0

はい、この場合にのみ動作します –

+0

Nealのソリューションをプログラマチックに使用して、私が進めていることを達成することができますが、あなたの答えに感謝します。 – Antoine

関連する問題