1

I have this array here (stressValues):

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

I'd like to find the array index value based on the property name of one of the contained objects, such as angeredoutsidecontrol, which would return 0

How can I achieve this?

This is what I have so far:

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
    }
  }
}
3
  • 1
    Can you show what you have done to achieve your goal? Commented Jul 17, 2017 at 21:13
  • Have you tried anything yet? Also, what if the array contains multiple object with the same property name. Do you return all indices or just one? Commented Jul 17, 2017 at 21:14
  • arr.map((e, i) => {e.index = i; return e}) Commented Jul 17, 2017 at 21:16

2 Answers 2

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'));

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, I was quite damn close too. Thanks a lot, I'll accept this as the answer when I'm able to.
2

If the objects have always only one property, you can use Object.keys with findIndex:

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

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

EDIT: If you want a more generic solution, you can use includes, so we check if the object includes, in its keys, the specified one:

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

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

4 Comments

This assumes only one key/value pair per object.
Yes, it works only in this case
I can use Neal's solution programatically to achieve what I'm going for but thanks for your answer.
@AnthonyMayfield I edited my answer with a more generic solution. Might be useful for you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.