您可以在将数据传递给 setRowData 之前对数据执行所需的任何转换:
agGrid.simpleHttpRequest( ... )
.then(data => {
// transform the data into whatever format you need
const rowData = data.reduce(...) // or whatever. not _necessarily_ reduce
gridOptions.api.setRowData(rowData);
})
根据您的评论,您将获得一个对象{},而不是discounts 的数组[]。我建议您在 API 端解决此问题,以便从一开始就获得一个数组,但假设这是不可能的,转换它是微不足道的。
给定一个对象x,调用Object.values(x) 将得到x 中的值 数组。例如:
const x = {
foo: 'a',
bar: 'b',
baz: 'c',
}
const v = Object.values(x);
// v is now ['a', 'b', 'c']
值也可以是对象。你得到一个对象数组:
const x = {
foo: { label: 'a', bang: 1 },
bar: { label: 'b', bang: 2 },
baz: { label: 'c', bang: 3 },
}
const v = Object.values(x);
// [{ label: 'a', bang: 1 }, { label: 'b', bang: 2 }, { label: 'c', bang: 3 }]
现在你有了一个数组,你可以使用像map这样的数组方法来转换它:
const bangs = v.map(value => value.bang);
// [1, 2, 3]
注意:所有这些示例都使用implicit return 语法来表示arrow functions。
如果您愿意,可以使用destructuring 来收紧上述表达式。下面的表达式在功能上等同于上面的表达式,没有重复“值”。在这种情况下并没有太大区别,但如果您需要输入对象中的多个字段,它就会开始累加。
const bangs = v.map(({bang}) => bang);
// [1, 2, 3]
解构还提供了一种在输入过程中重命名字段的机制。下面的示例将bang 重命名为x 并返回一个具有x 属性的对象:
// v = [{ label: 'a', bang: 1 }, { label: 'b', bang: 2 }, { label: 'c', bang: 3 }]
const bangs = v.map(({bang: x}) => ({x}));
// [{x: 1}, {x: 2}, {x: 3}]
您可以使用多个字段进行这种速记解构/重命名。在这里,我们将bang 重命名为x,将label 重命名为y,并返回一个具有这些属性的新对象:
// v = [{ label: 'a', bang: 1 }, { label: 'b', bang: 2 }, { label: 'c', bang: 3 }]
const bangs = v.map(({bang: x, label: y}) => ({x, y}));
// [{x: 1, y: 'a'}, {x: 2, y: 'b'}, {x: 3, y: 'c'}]
使用这种方法,您可以将discounts 对象中的BasePrice 和SalePrice 字段重新映射为您需要的任何格式。在下面的示例中,我将它们重新映射到具有x 和y 属性的对象数组。我不知道这就是 agGrid 所期望的,但调整它以满足您的需求应该很简单。
// function that converts the sample data format to an array of
// coordinates, e.g. [{ x: 555, y: 999 }, { x: 123, y: 456 }]
function transform (input) {
return Object.values(input.discounts)
.map(({BasePrice: x, SalePrice: y}) => ({x, y}))
}
fakeApiRequest() // simulate the request
.then(apiData => {
const rowData = transform(apiData); // transform the response data
show(rowData); // show the result
})
//-------
// everything below is just utility and convenience stuff
// for the demo. mostly irrelevant/ignorable for your purposes
//-------
// sample data
const sampleData = {
"discounts": {
"0": { "BasePrice": "1499", "SalePrice": "449" },
"1": { "BasePrice": "1299", "SalePrice": "519" }
}
}
// simulates an api request; waits a moment then resolve with sample data.
// not really relevant to your issue; just hand-waving for the demo
async function fakeApiRequest () {
return new Promise(resolve => {
setTimeout(() => resolve(sampleData), 100)
});
}
// irrelevant. just a convenience utility for showing the output.
function show(d) {
document.querySelector('pre').innerHTML = JSON.stringify(d, null, 3);
}
<pre></pre>