2

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
1
  • What was the error/problem you got? Commented Oct 27, 2017 at 9:15

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.