CourtneyJ
CourtneyJ

Reputation: 508

Checking an object that contains arrays of objects for a value

I see this question has been touched on a lot on stack overflow but I can't seem to find one that helps my issue. I have an object that contains many arrays with objects nested inside. I need to find the key of the array that contains the object that a usersID. Ive tried .filter and for in loops but I keep getting errors.

My data looks like this :

{
  FL: [{id: "mp-2d24973e-c610-4b1c-9152...}{id...}],
  TX: [{id: "mp-2d24973e-c610-4b1c-9152...}{id...}],
  LA: [{id: "mp-2d24973e-c610-4b1c-9152...}{id...}],
}

Is there a method that allows me to check for a value inside the arrays and if it is found returns the key to that array ie. FL or TX?

const practices = data.items
for (const [key, value] of Object.entries(practices)){
          console.log(key, value, "KEYVALUE")
          if(value.id === currentUser.currentPracticeID){
            console.log(key)
          }
        }

Of course this code doesnt work but this what Ive tried so far. Im still new to dev so any point in the right direction would be great.

Upvotes: 1

Views: 758

Answers (4)

Kinglish
Kinglish

Reputation: 23654

A simple filter() inside of a for...in loop would do it. After looking at the other answers, I should say this will return the first matching ID, rather than an array of all matching ID's like @Barmars answer

const practices = {
  FL: [{id: "mp-2d24973e-c610-4b1c-9152"},{id:"3"}],
  TX: [{id: "mp-2d24973e-c610-4b1c-9153"},{id:"4"}],
  LA: [{id: "mp-2d24973e-c610-4b1c-9154"},{id:"5"}],
}

const findUserKey = (u) => {
  for (const key in practices) {
    if (practices[key].filter(mp => mp.id === u.currentPracticeID).length>0) return key
  }
  return false;
}

let currentUser = {currentPracticeID: "mp-2d24973e-c610-4b1c-9154"}
let check_mp = findUserKey(currentUser)
console.log(check_mp)

Upvotes: 1

dev
dev

Reputation: 841

Here is how I would do it:

const data = {
    FL: [{id: 'ab'}, {id: 'cd'}, {id: 'ef'}],
    TX: [{id: 'hi'}, {id: 'jk'}, {id: 'lm'}],
    LA: [{id: 'no'}, {id: 'pq'}, {id: 'rs'}]
};

const findKey = (id) => {
    let foundKey;
    Object.entries(data).some(([key, objects]) => {
        if (objects.find(object => object.id === id)) {
            foundKey = key;
            return true;
        }            
    });

    return foundKey;
};

console.log(`The data: ${JSON.stringify(data)}`);
console.log(`Looking for object with ID "jk": ${findKey('jk')}`);

You loop through the entries of your data, so you have the key and the objects for that key. You simply use objects.find to see which object matches the ID you're looking for. I would use array.some for this as it stops the loop when you return true, and foundKey will simply be falsy if nothing is found.

Upvotes: 0

Barmar
Barmar

Reputation: 781340

filter() is an array method, practices is an object. You need to use Object.entries() to get an array of keys and values.

Then you can use .some() to test if any of the objects in the nested array contain the ID you're looking for.

const practices = {
  FL: [{
    id: "mp-2d24973e-c610-4b1c-9152"
  }, {
    id: "mp-2d24973e-c610-4b1c-9153"
  }],
  TX: [{
    id: "mp-2d24973e-c610-4b1c-9154"
  }, {
    id: "mp-2d24973e-c610-4b1c-9155"
  }],
  LA: [{
    id: "mp-2d24973e-c610-4b1c-9156"
  }, {
    id: "mp-2d24973e-c610-4b1c-9157"
  }]
};

let currentPracticeID = "mp-2d24973e-c610-4b1c-9156";
const states = Object.entries(practices).filter(([key, arr]) => arr.some(({
  id
}) => id == currentPracticeID)).map(([key, arr]) => key);

console.log(states);

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28424

You can use Object#keys to get the list of object keys, Array#find to iterate over this list, and Array#findIndex to check if the array at each iteration has the userId you're searching for:

const getKeyOfUserId = (obj = {}, userId) => 
  Object.keys(obj).find(key =>
    obj[key].findIndex(({ id }) => id === userId) >= 0
  );
  
const obj = {
  FL: [{id: "mp-2d24973e-c610-4b1c-9152"},{id:"mp-2d24973e-c610-4b1c-9153"}],
  TX: [{id: "mp-2d24973e-c610-4b1c-9154"},{id:"mp-2d24973e-c610-4b1c-9155"}],
  LA: [{id: "mp-2d24973e-c610-4b1c-9156"},{id:"mp-2d24973e-c610-4b1c-9157"}]
};
console.log( getKeyOfUserId(obj, "mp-2d24973e-c610-4b1c-9156") );

Upvotes: 1

Related Questions