0

I am trying to add all node names to a list if they do not already exist in the list.

I know my if statement is incorrect here, but not sure exactly what is wrong.

nodeList = []

var data = [
    {
    "something": "something",
    "stages": [{
                "node": {"name": "test0"},
                "status": {"name": "test"},
                "time": {"name": "test"}
               },{
                "node": {"name": "test1"},
                "status": {"name": "test"},
                "time": {"name": "test"}
               }]
     }
];

data.forEach(obj =>
  obj.stages.forEach(stage => if (nodeList.indexOf(stage.node.name) > -1) {
  nodeList.push({stage.node.name})
  );

2 Answers 2

1

You had a few syntax errors and you need to test:

if (nodeList.indexOf(stage.node.name) < 0)

not > -1. You want to add the value when it's not there, which means indexOf will return -1. I think this is what you're after:

nodeList = []

var data = [
    {
    "something": "something",
    "stages": [{
                "node": {"name": "test0"},
                "status": {"name": "test"},
                "time": {"name": "test"}
               },{
                "node": {"name": "test1"},
                "status": {"name": "test"},
                "time": {"name": "test"}
               }]
     }
];

data.forEach(obj =>
  obj.stages.forEach(stage => {
    if (nodeList.indexOf(stage.node.name) < 0) {
      nodeList.push(stage.node.name)
    }
  }))

  console.log(nodeList)

If you can use ES6 things would be easier — you could use a Set and avoid the test altogether:

nodeList = new Set

data.forEach(obj =>
  obj.stages.forEach(stage => nodeList.add(stage.node.name)
))

Then you could iterate the Set or spread it into an array depending on what you're doing next.

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

Comments

1

Array.prototype.indexOf(element) returns -1 if element wasn't found.

In your case, you are using > -1 which is the contrary.

There is an updated version of your code:

var nodeList = []

var data = [{
  "something": "something",
  "stages": [{
    "node": {"name": "test0"},
    "status": {"name": "test"},
    "time": {"name": "test"}
   }, {
    "node": {"name": "test1"},
    "status": {"name": "test"},
    "time": {"name": "test"}
  }]
}];

data.forEach((obj) => {
  obj.stages.forEach((stage) => {
    if (nodeList.indexOf(stage.node.name) === -1) {
      nodeList.push(stage.node.name);
    }
  });
});

console.log(nodeList);

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.