在我的数组中是这样的,
var myColumnDefs = [
{a: "hh", b: "hh", c: "jk", d: "ggh", e: "hvh"},
{a: "dd", b: "gg", d: "nn", e: "rr", f: "jj"},.....
]
我想过滤数据并在新数组中插入数据
var newarray = {a,b,c,d,e,f}
&安培;另一个数组
var mysecondarray = [
{hh,hhjk,ggh,hvh},
{dd,gg,nm,rr,jj},....
]
答案 0 :(得分:1)
您可以使用 map()
和 indexOf()
并执行此类操作
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>');
&#13;
答案 1 :(得分:1)
假设您希望结果在数组中,那么这应该有效。结果是在一个对象中进行进一步处理。
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>');
&#13;
答案 2 :(得分:0)
假设mysecondarray的数组数组的顺序相同。
试
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));