david
david

Reputation: 6785

how to add string to a list inside a for loop using javascript?

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

Upvotes: 0

Views: 414

Answers (2)

muZk
muZk

Reputation: 3038

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

Upvotes: 1

Mark
Mark

Reputation: 92440

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.

Upvotes: 1

Related Questions