简体   繁体   中英

How to push two Arrays(having json objects) into a new Array

I Want These two arrays into a new array and then i want to print the final array along with all 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; }```

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

you can use this trick

         z.push(...y);

         const filteredArray = z.filter(each => each.appName == 'CapLogix');
          console.log(filteredArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM