简体   繁体   中英

how to filter data in array loop

In my array is like this,

var myColumnDefs = [

    {a: "hh", b: "hh", c: "jk", d: "ggh", e: "hvh"},

    {a: "dd", b: "gg", d: "nn", e: "rr", f: "jj"},.....
]

I want to filter data and insert data in new array like this

var newarray = {a,b,c,d,e,f}

& another array

var mysecondarray = [

                {hh,hhjk,ggh,hvh},

                {dd,gg,nm,rr,jj},....
]

You can use map() and indexOf() and do something like this

 var myColumnDefs = [ { a: "hh", b: "hh", c: "jk", d: "ggh", e: "hvh" }, { a: "dd", b: "gg", d: "nn", e: "rr", f: "jj" } ]; var arr1 = [], arr2 = []; // iterate over `myColumnDefs` array and generate value array arr2 = myColumnDefs.map(function(v, i) { // get keys from object var keys = Object.keys(v); // iterate over key values and generate the value array and then return return keys.map(function(k) { // check key value is in `arr1`, push if not if (arr1.indexOf(k) == -1) arr1.push(k); // return corresponding value based on key return v[k]; }); }); document.write('First Array : <pre>' + JSON.stringify(arr1, null, 3) + '</pre> Second Array : <pre>' + JSON.stringify(arr2, null, 3) + '</pre>'); 

Assuming you want the result in arrays, then this should work. The result is in an object for further processing.

 var myColumnDefs = [{ a: "hh", b: "hh", c: "jk", d: "ggh", e: "hvh" }, { a: "dd", b: "gg", d: "nn", e: "rr", f: "jj" }], result = function (array) { var r = { keys: [], data: [] }; array.forEach(function (a) { r.data.push(Object.keys(a).map(function (k) { !~r.keys.indexOf(k) && r.keys.push(k); return a[k]; })); }); return r; }(myColumnDefs); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>'); 

Assuming that mysecondarray is having an array of array of values in the same order.

try

var columns = {}; //newarray 
var values = []; //mysecondarray 
myColumnDefs.forEach(function(value){

   var arr = [];
   for (var key in value)
   {
      columns[key] = true;
      arr.push(value[key]);
   }
   values.push(arr);

})
console.log("columns are " + JSON.stringify(Object(columns).keys, 0, 4));
console.log("values are " + JSON.stringify(values, 0, 4));

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