I'm following this tutorial to "detect" if a unique number is in an array object. This number is a string.
I'm used to detect
in Ruby on Rails so I look for the equivalent in React (JavaScript):
ES6:
...
// this will be "data" in "this.props.data"
data = [
{
id: 1,
order_id: "44",
name: "Some order number name",
},
{
id: 2,
order_id: "65",
...,
}
]
// let num = "44"; Just for this example
renderCreditNote(num){
if (num instanceof this.props.data) {
return num.map(function(p){
return p.order_id
});
}
}
render(){
return({this.renderCreditNote().bind(this)})
}
...
In reality, this will look like this: this.renderCreditNote(this.state.num).bind(this)
So if this num
is in the Array, display only that array. Am I doing this the right way? The error is:
Uncaught TypeError: Right-hand side of 'instanceof' is not callable
I don't know Ruby, but based on the description of detect
it seems you are looking for array.find in JavaScript. .find
iterates over an array - if it finds the item you are looking for it returns it and stops iterating, if it does not find anything undefined
is returned.
So for example:
renderCreditNote(num){
return this.props.data.find(function(p){
return num === p.order_id;
});
}
Here's a fiddle: https://jsfiddle.net/7ykt9ze3/
Some ES6 prettification:
renderCreditNote(num){
return this.props.data.find(p => num === p.order_id);
}
Be aware that this isn't completely supported in slightly older browsers, I know from experience IE11 doesn't have it. However it is definitely worth the polyfill.
About the blog you linked - without going into prototypical inheritance, instanceof
basically returns true/false if the input is of the data structure. In the blog you linked they are detecting whether or not the input is an object or an array - but only so they can take different actions depending on that input. So if it's an object they simply return the field on that object, if it's an array they iterate over the array with .map
and return all the names of those objects in that array.
Edit to check render method:
render(){
return(<div>{JSON.stringify(this.renderCreditNote().bind(this))}</div>)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With