-1

I want to get the array items which contains appName: "CapLogix" into a new array.The thing which you have to keep in mind is the Array Objects are JSON Objects.

var z = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "970",
  "envName": "UAT4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "971",
  "envName": "UAT4"
}];

var y = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "959",
  "envName": "SIT-4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "963",
  "envName": "SIT-4"
}];

This is what I tried so far:

z.push(y);

for (var i = 0; i <= z.length; i++) {
    document.getElementById("sa").innerHTML += "appId  :" + z[i].appId + "<br>" + " appName  : " + z[i].appName + "<br>" + "envId  :" + z[i].envId + "<br>" + " envName  : " + z[i].envName;
}

1 Answers1

1

You can make use of spread operator (ES6), this will spread all the items of array into new array Example below

const z = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "970",
  "envName": "UAT4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "971",
  "envName": "UAT4"
}];

const y = [{
  "appId": "1",
  "appName": "CapLogix",
  "envId": "959",
  "envName": "SIT-4"
}, {
  "appId": "73",
  "appName": "ConfigBuilder",
  "envId": "963",
  "envName": "SIT-4"
}];

const finalArray = [...z, ...y];
console.log(finalArray);

If you want to push all values in to first array (z), you can do something like this

z.push(...y);
console.log(z);

So you will end up with z containing all items of both the arrays

EDIT

you can use filter to filter items and get new array, To get the array items which contains appName: "CapLogix" (Example below)

After merging array you can apply filter on it.

const z = [{
      "appId": "1",
      "appName": "CapLogix",
      "envId": "970",
      "envName": "UAT4"
    }, {
      "appId": "73",
      "appName": "ConfigBuilder",
      "envId": "971",
      "envName": "UAT4"
    }];

    const y = [{
      "appId": "1",
      "appName": "CapLogix",
      "envId": "959",
      "envName": "SIT-4"
    }, {
      "appId": "73",
      "appName": "ConfigBuilder",
      "envId": "963",
      "envName": "SIT-4"
    }];

z.push(...y);

const filteredArray = z.filter(each => each.appName == 'CapLogix');
console.log(filteredArray);
geeky
  • 71
  • 1
  • 13
  • 2
    What's the purpose of the function `filter` here? – Ele Feb 18 '20 at 09:31
  • 1
    @Ele i use it to filter the array objects(having appName == 'CapLogix') , instead of using (for loop and condition) , it is very fast and short. – geeky Feb 18 '20 at 09:35
  • I understand, but how this helps the OP according to the posted question? – Ele Feb 18 '20 at 09:47