Home > Enterprise >  I am having trouble splicing an element from a nested json object
I am having trouble splicing an element from a nested json object

Time:09-14

I have a JavaScript file called Splice.js

var searchresponse = [{
  "items": [{
      "employeeId": "ABC",
      "type": "D",
      "alive": "Yes"

  }, {
      "employeeId": "DEF",
      "type": "D",
      "alive": "Yes"

  }, {
      "employeeId": "NPK",
      "type": "D",
      "alive": "Yes"

  }, {
      "employeeId": "PKN",
      "type": "A",
      "alive": "Yes"
  }],
  "more": false
}];
var data1=["ABC","DEF"];
var items=searchresponse[0].items;
var i=items.length;
while (i--) {
    if(data1.indexOf(items[i].employeeId)!=-1){
        items.splice(i,1);
    }
}
console.log(searchresponse[0].items);

How could I achieve the same result from a nested JSON object like the one below?

var searchresponse = [{
  "order": [
      {
          "items": [
              { 
                  "route": "foo", 
                  "display": "foo" ,
                  "employeeId": "ABC"
              },
              { 
                  "route": "bar", 
                  "display": "bar" ,
                  "employeeId": "DEF"
              },
              { 
                  "route": "baz", 
                  "display": "baz" ,
                  "employeeId": "GHI"
              },
              { 
                  "route": "qux", 
                  "display": "qux" ,
                  "employeeId": "JKL"
              }
          ]
      }
  ],
  "more": false
}];

var data1=["ABC","DEF"];
var items=searchresponse[0].items;
var i=items.length;
while (i--) {
    if(data1.indexOf(items[i].employeeId)!=-1){
        items.splice(i,1);
    }
}
console.log(searchresponse[0].items);

I have been having a difficult time with this and really could appreciate a second pair of eyes to see where I am messing this one up! Any help would be greatly appreciated!

CodePudding user response:

Just address the right property: searchresponse[0].order[0].items

var searchresponse = [{
  "order": [{
    "items": [{
        "route": "foo",
        "display": "foo",
        "employeeId": "ABC"
      },
      {
        "route": "bar",
        "display": "bar",
        "employeeId": "DEF"
      },
      {
        "route": "baz",
        "display": "baz",
        "employeeId": "GHI"
      },
      {
        "route": "qux",
        "display": "qux",
        "employeeId": "JKL"
      }
    ]
  }],
  "more": false
}];

var data1 = ["ABC", "DEF"];
var items = searchresponse[0].order[0].items;
var i = items.length;
while (i--) {
  if (data1.indexOf(items[i].employeeId) != -1) {
    items.splice(i, 1);
  }
}
console.log(searchresponse[0].order[0].items);

  • Related