简体   繁体   中英

How to filter array of objects and get filtered object value

I have an array model as below:

nodes:[
 { id: 1, label: 'label1'},
 { id: 2, label: 'label2'},
 { id: 3, label: 'label3'}
]

I whant to get the label of node filtering by id

I tried the next way, but dont get it work

const selectedNode = 2;

const nodeLabel = nodes.filter(({id}) => id.label ? id === selectedNode) // its filter here

You can use find method by passing a callback provided function.

The find() method returns the value of the first element in the array that passed the provided testing function. Otherwise undefined is returned.

 let nodes=[ { id: 1, label: 'label1'}, { id: 2, label: 'label2'}, { id: 3, label: 'label3'} ]; let id=2; let node = nodes.find(a=>a.id == id); console.log(node ? node.label : 'id not found'); 

nodes.find(node => node.id === selectedNode).label

You were quite close.

This line

nodes.filer(({id}) => id.label ? id === selectedNode)

has few issues ( assuming filer was just a typo )

  • It is comparing an integer with an object. ( id is the object here)

  • filter will give you the list of objects rather than its property label .

  • You were comparing label with id value.

  • {id} to be replaced by id .

Just modify this to

nodes.filter( (id) => id.id === selectedNode )[0].label

Demo

 var nodes = [ { id: 1, label: 'label1'}, { id: 2, label: 'label2'}, { id: 3, label: 'label3'} ]; var selectedNode = 2; console.log( nodes.filter( (id) => id.id === selectedNode )[0].label ); 

There's a few ways you could do what you're trying to do. Here are a couple using native Array methods.

  1. Chain filter and map and destructure the returned array.

     const [nodeLabel] = nodes .filter(({id}) => id === selectedNode) .map(({label}) => label) 
  2. Use reduce

     const nodeLabel = nodes .reduce((returnValue, item) => { if (item.id === selectedNode) return item.label return returnValue }) 

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