1

Im fairly new to javascript and im trying to find an object of an array i created by the configID property. I used the method find() for this.

JS Code:

var configurationArray = flow.get("configurationArray") || [];
var configurationId = msg.topic.split("/")[1];
var configuration = {
  configID: this.configurationID,
  configurationModules: this.MSGesture.payload
};

if(!configurationArray.find(x => x.configID == this, configurationId)){
  configurationArray.push(this.configuration);
} else {
  //to do
}

I am using node-red which gives me flow and msg.

The Error i get:

Cannot read property 'configId' of undefined

Any help is appreciated

3
  • 2
    Error clearly states value of x is undefined, just change it to x && x.configId Commented Jul 16, 2019 at 7:32
  • Also check if variable is defined and its length if (configurationArray && !!configurationArray.length && configurationArray.find(...) ) Commented Jul 16, 2019 at 7:33
  • @CodeManiac Your answer also worked, thanks. Commented Jul 16, 2019 at 8:42

1 Answer 1

2

You could destructure the property and add a default object.

Then take some instead of find, because you need only the check.

At last, omit this and take directly the value.

if (!configurationArray.some(({ configID } = {}) => configID === configurationId)) {
    configurationArray.push(this.configuration);
} else {
    //to do
}

If you like to have an abstract callback, you could take a closure over configurationId, like

const hasId = id => ({ configID } = {}) => configID === id;

if (!configurationArray.some(hasId(configurationId)) {
    configurationArray.push(this.configuration);
} else {
    //to do
}
Sign up to request clarification or add additional context in comments.

2 Comments

This worked. Thanks! Could you please explain what the ({ configID } = {}) does? I dont completely understand what it does infront of the =>.
it's a destructuring assignment with a default parameters. it takes an object, or if the value is undefined, then the default object and pulls out configID from the object

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.