user4584963
user4584963

Reputation: 2533

Return array of values from object based on array

I have an object that looks like this

I would like to return an array of wsnames based on altnames. For example, I provide an array ["AAVEETH", "AAVEXBT"] and get back ["AAVE/ETH", "AAVE/XBT"].

I figured out how to use lodash __.filter like this

 const wsnames = _.filter(
    obj,
    (item) => item.altname === 'AAVEETH' || item.altname === 'AAVEXBT'
  )

but this only returns the full object entry. Also, my input array won't be known beforehand.

Upvotes: 0

Views: 275

Answers (2)

Fahad Subzwari
Fahad Subzwari

Reputation: 2325

You can just use Object.values and array.filter to achieve this.

let arr = ["AAVEETH", "AAVEXBT"]
let masterObj = [....] // your object having all data
result = []
arr.forEach(i => {
 let found =  Object.values(masterObj).filter(i => i.altname)[0]
  if(found){
    result.push(i.wsname)
  }
})

In above code i am just looping on your altname array on behalf of which you want to get wsname array and in that i am using object.values to get all values as array and then i am doing filteration to get the wsname of the matching object that have matching altname

Upvotes: 0

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20944

First turn the values of the object into an array of values with Object.values(). Now you can use array methods like filter to filter out the unwanted values and map to create a new array with only the wsname properties.

const wsNames = Object.values(obj)
  .filter(({ altname }) => altname === 'AAVEETH' || altname === 'AAVEXBT')
  .map(({ wsname }) => wsname);

Now you can turn this logic into a function in which you pass the object you want to filter from and an array of altname values that you want to get the wsname values from.

const getWsNames = (obj, altNames) => Object.values(obj)
  .filter(({ altname }) => altNames.includes(altname))
  .map(({ wsname }) => wsname);

const wsNames = getWsNames(obj, ['AAVEETH', 'AAVEXBT']);

Upvotes: 1

Related Questions