如何从以下内容创建JSON。 (我使用map函数来遍历数据,但是无法在react中构建JSON结构。我熟悉使用LINQ和list在C#中进行构建,但是由于我对ReactJS还是天真,所以不确定如何实现。)
const prodData =
{
"id": 1,
"brandName":"Brand A",
"steps": [
{
"stepsID": "stepsID1",
"businessType": [
{
"businessType": 1,
"businessName": "Product 1",
"products": [
{
"productID": 11,
"productName": "product 11",
"productValue": 1,
},
{
"productID": 12,
"productName": "product 12",
"productValue": 2,
}
]
}
],
{
"stepsID": "stepsID2",
"businessType": [
{
"businessType": 2,
"businessName": "Product 2",
"products": [
{
"productID": 21,
"productName": "product 21",
"productValue": 3,
},
{
"productID": 22,
"productName": "product 22",
"productValue": 4,
}
]
}
]
}
}
}
如下构建反应树胡子树的数据:
const sdata = {
name: 'Brand A',
toggled: true,
children: [
{
name: 'stepsID1',
children: [
{
"businessName": "Product 1",
"products": [
{
"productID": 11,
"productName": "product 11",
"productValue": 1,
},
{
"productID": 12,
"productName": "product 12",
"productValue": 2,
}
]
]
}
],
name: 'stepsID2',
children: [
{
"businessName": "Product 2",
"products": [
{
"productID": 21,
"productName": "product 21",
"productValue": 3,
},
{
"productID": 22,
"productName": "product 22",
"productValue": 4,
}
]
]
}
]
};
答案 0 :(得分:0)
下面的代码示例会将您的输入数据转换为所需的格式。注意:拥有C#和LINQ的背景知识,您可能会熟悉LINQ的.Select()
方法。在JavaScript中,.map(fn)
大致等效于.Select(fn)
。
/*
Your input data (corrected from malformed data in your question)
*/
const prodData = {
'id': 1,
'brandName': 'Brand A',
'steps': [{
'stepsID': 'stepsID1',
'businessType': [{
'businessType': 1,
'businessName': 'Product 1',
'products': [{
'productID': 11,
'productName': 'product 11',
'productValue': 1,
},
{
'productID': 12,
'productName': 'product 12',
'productValue': 2,
}
]
}],
}, {
'stepsID': 'stepsID2',
'businessType': [{
'businessType': 2,
'businessName': 'Product 2',
'products': [{
'productID': 21,
'productName': 'product 21',
'productValue': 3,
},
{
'productID': 22,
'productName': 'product 22',
'productValue': 4,
}
]
}]
}]
}
/*
Helper function checks input data is array, guarantees an array is returned
*/
function asArray(object) {
return Array.isArray(object) ? object : []
}
/*
Inline mapping of input data, to yield data in desired shape
*/
const sdata = {
name: prodData.brandName || '',
toggled: true,
children: asArray(prodData.steps)
.map(step => {
const children = asArray(step.businessType)
.map(businessType => {
const products = asArray(businessType.products)
.map(product => {
return {
productID: product.productID,
productName: product.productName,
productValue: product.productValue,
}
})
return {
businessName: businessType.businessName,
products
}
})
return {
name: step.stepsID,
children,
}
}),
}
console.log('input', JSON.stringify(prodData, null, ' '))
console.log('output', JSON.stringify(sdata, null, ' '))