cbdeveloper
cbdeveloper

Reputation: 31485

Something equivalent to Array.find() to work on object properties instead of array elements

Given an object like this:

const someObject = {
  ID_1: {
    // OTHER STUFF,
    index: 1
  },
  ID_2: {
    // OTHER STUFF,
    index: 2
  },
  ID_3: {
    // OTHER STUFF,
    index: 3
  },
  // ETC
}

I need to grab the inner object that has index === 2

If this was an array, I could use Array.find, for example.

const element = someArray.find((item) => item.index === 2);

What is the easier way of doing that to an object? Do I need to convert it to array before? Is it the best way to go?

Upvotes: 1

Views: 823

Answers (2)

mplungjan
mplungjan

Reputation: 178375

This would get the entry

const someObject = { ID_1: { "OTHER STUFF":"Other 1", index: 1 }, ID_2: { "OTHER STUFF":"Other 2", index: 2 }, ID_3: { "OTHER STUFF":"Other 3", index: 3 } };

console.log(
  Object.entries(someObject).find(([key,value]) => value.index===2); // note === needs an int here
)

Thes would get the inner entry

const someObject = { ID_1: { "OTHER STUFF":"Other 1", index: 1 }, ID_2: { "OTHER STUFF":"Other 2", index: 2 }, ID_3: { "OTHER STUFF":"Other 3", index: 3 } };

console.log(
  Object.values(someObject).find(value => value.index===2)
)

Upvotes: 2

brk
brk

Reputation: 50336

You can iterate the object and check if the object have the key index and if it has value 2 then return the object

const someObject = {
  ID_1: {
    // OTHER STUFF,
    index: 1
  },
  ID_2: {
    // OTHER STUFF,
    index: 2
  },
  ID_3: {
    // OTHER STUFF,
    index: 3
  },
  // ETC
}


function recursive(obj) {
  for (let keys in obj) {
    if (typeof(obj[keys]) === 'object' && obj[keys].hasOwnProperty('index') && obj[keys].index === 2) {
      return obj[keys]
    }
  }

}
console.log(recursive(someObject))

Upvotes: 0

Related Questions