TransWikia.com

Return array of values from object based on array

Stack Overflow Asked by user4584963 on January 9, 2021

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.

2 Answers

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

Correct answer by Emiel Zuurbier on January 9, 2021

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

Answered by Fahad Subzwari on January 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP