我正在尝试使用不同的数据迭代JSON。
我正在使用Angular2,Ag-grid Master详细信息,详细信息来自CellRendererParams:
当我尝试迭代我的JSON以获取数据时,我遇到了问题。
ngOnInit() {
this.gridOptions = <GridOptions>{};
this.detailCellRendererParams = {
detailGridOptions: {
onGridReady: function(params) {
params.api.sizeColumnsToFit();
}
},
getDetailRowData: function(params) {},
template: function(params) {
console.log('before');
console.log('datas ', params.data.masterdetail);
for (const valor of params.data.masterdetail) {
console.log('eyy');
if (params.data.masterdetail.hasOwnProperty(valor)) {
console.log('este valor es : ', valor);
}
}
console.log('after');
// console.log('template ', params.data.masterdetail);
return '<div class="aggrid--full-row-container">' + '<div ref="eDetailGrid" </div>' + 'asereje ' + '</div>';
}
};
}
永远不要加入for ...
您可以看到我如何在4
console.log('datas ', params.data.masterdetail);
数据
新代码更新:
console.log('before');
console.log('datas ', params.data.masterdetail);
const objects = JSON.parse(params.data.masterdetail);
for (const obj of objects) {
const keys = Object.keys(obj);
keys.forEach(key => {
console.log(obj[key]);
});
}
console.log('after');
错误:
ERROR SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
at template (projectunits.component.ts:43)
at DetailCellRenderer.webpackJsonp../node_modules/ag-grid-enterprise/dist/lib/rendering/detail/detailCellRenderer.js.DetailCellRenderer.selectAndSetTemplate (detailCellRenderer.js:96)
at DetailCellRenderer.webpackJsonp../node_modules/ag-grid-enterprise/dist/lib/rendering/detail/detailCellRenderer.js.DetailCellRenderer.init (detailCellRenderer.js:33)
at ComponentResolver.webpackJsonp../node_modules/ag-
我得到的数据是un file.json。 构建我的Json:
{
"headers": [
"headerName": "asdasd",
], //end headers
"datas": [
"idaam": "11",
"idorigen": "11",
"masterdetail": {
"child1": {
"name": "I AM",
"age": "1"
},
"child2": {
"name": "YOU ARE",
"age": "2"
},
"child3": {
"name": "HE IS",
"age": "3"
},
} //end masterdetail
]//end datas
}//end JSON
答案 0 :(得分:0)
看起来像你的json数据不能尝试
params.data.masterdetail.forEach((data)=>{
});
作为它的json,你应该把json分成对象,然后在那个
上做 const objects = JSON.prase(JSON.stringify(params.data.masterdetail));
for(const obj of objects){
const keys = Object.keys(obj);
keys.forEach((key)=> {
console.log(obj[key]);
});
}
答案 1 :(得分:0)
这是我的回复。在解析之前,您可以检查数据是Object还是简单String。此代码假定您确定获得的是JSON而不是数组
const objects = (typeof params.data.masterdetail == 'object') ? JSON.parse(params.data.masterdetail) : params.data.masterdetail;
for (const obj in objects) {
const data = objects[obj];
//Bellow if each attribute data
}