fasenberg
fasenberg

Reputation: 3095

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

Upvotes: 2

Views: 1751

Answers (4)

Marc Davies
Marc Davies

Reputation: 266

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
      })
    

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

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

Upvotes: 1

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

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

Upvotes: 3

Naisheel Verdhan
Naisheel Verdhan

Reputation: 5133

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

Upvotes: 1

Related Questions