简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM