我有一个数组对象
MainArray = {"Data":
[{"Group": "GroupA"},{"Group": "GroupB"}]
}
然后我遍历数组并创建一个新的
let _newArray : any[] = [];
MainArray.Data.forEach(item => {
_newArray.push({
groupname : item.Group,
columns: ["column1","column2","column3"]
});
//loop through _newArray.columns
});
然后我需要遍历Main Array循环内的new Array的列
并从另一个数组中推送一个数组。
SecondArray = [{group: "GroupA", value: "firstfield", count: 14 },{group: "GroupA", field: "secondfield", count:23 },{group: "GroupB", field: "randomfield", count:1 }]
所以输出应该是
_newArray = [{
groupname: "GroupA",
columns: ["column1","column2","column3"]
col1: [{"firstfield":14, "secondfield": 23 }]
col2: "",
col3: ""
},{GroupB...}]
我尝试了什么:
Object.keys( _newArray[0].columns).forEach( function(value, key) {
console.log(this._SecondArray[item.Group])
// push 'col + index: [Second Array]'
});
答案 0 :(得分:0)
在SecondArray中,第一个对象具有“值”键。我以为是“场”
let MainArray = {
"Data":
[{ "Group": "GroupA" }, { "Group": "GroupB" }]
}
// First push
let _newArray = [];
MainArray.Data.forEach(item => {
_newArray.push({
'groupname': item.Group,
'columns': ["column1", "column2", "column3"]
})
})
let SecondArray = [{ group: "GroupA", field: "firstfield", count: 14 }, { group: "GroupA", field: "secondfield", count: 23 }, { group: "GroupB", field: "randomfield", count: 1 }];
// Second push
_newArray.forEach(item => {
console.log(item)
let i = 1;
item.columns.forEach(cols => {
console.log(cols)
if (i == 1) {
item["col" + i] = {}
SecondArray.forEach(subItem => {
console.log(subItem)
if (subItem.group == item.groupname) {
item["col" + i][subItem.field] = subItem.count
}
})
i++
} else {
item["col" + i++] = ""
}
})
})
console.log(_newArray);