BeeNag
BeeNag

Reputation: 1844

finding a value in an object

I have an object:

{
   id: 16, 
   defs: {
      name: "Depot (Float)", field: "Depot"
   }
}

And an array (which can have more than one object in it but for the purposes of this only has one):

[
  {
    Percentage Monthly Potential: 1, 
    Area Manager: "Ashar", 
    Business Unit: "Retail", 
    Cust no: 68345, 
    Depot Name: "Leicester", 
    Group Number: "", 
    Depot: 14, 
    Target: 46100
  }
]

What I need to do is take the field value from the object and use it to find the key that it matches in the second object and retrieve the value of it, so in this case I should be getting 14.

Any help with this would be much appreciated.

Thanks for your time.

Upvotes: 0

Views: 54

Answers (1)

Elod Szopos
Elod Szopos

Reputation: 3526

If you are using ES6, you can try this:

const field = lookupObject.defs.field;

const matches = array.map(arrayItem => {
    return {
        field,
        value: arrayItem[field]
    }
});

The matches array will contain the data you are interested in.

Upvotes: 1

Related Questions