[英]How to convert nested array of object into Json object
使用React 或 JavaScript如何将下面的示例嵌套对象数组转换为 JSON:有什么解决方案吗? 对于这个问题的反应? 我尝试通过 map 解决这个问题,但是,在变量中它将存储最后一个值,剩余的子对象被覆盖
Here i want to bind Json data into Fluent UI detailList with reference of filed name later i need to export in different format like excel... for exporting excel we have to call data by filed name thats the reason whatever nested Json data is there i试着制作简单的 Json 格式
Fluent 表示例: https://developer.microsoft.com/en-us/fluentui#/controls/web/detailslist
{
"msg": "hello world",
"success": "true",
"Details": [
{
"group": "grp1",
"personDetails": [
{
"firstName": "abc",
"lastName": "xyz",
"mobile": 12334,
"state": "abc"
}
]
},
{
"group": "grp1",
"personDetails": [
{
"firstName": "abc",
"lastName": "xyz",
"mobile": 12334,
"state": "abc"
},
{
"firstName": "abc",
"lastName": "xyz",
"mobile": 12334,
"state": "abc"
}
]
}
]
}
如何将上面的 Json object 转换为以下格式:Expexted Json 格式
[
{
firstName: "abc",
lastName: "xyz",
mobile: 12334,
state: "abc",
},
{
firstName: "abc",
lastName: "xyz",
mobile: 12334,
state: "abc",
},
{
firstName: "abc",
lastName: "xyz",
mobile: 12334,
state: "abc",
},
];
我找到了解决方案,如果有人遇到此类问题,您可以通过 go 彻底执行以下步骤。
var array = [];
source["Details"].forEach((i) => array.push(...i["personDetails"]));
console.log(array);
这是使用对象扫描的灵活易读的解决方案
// const objectScan = require('object-scan'); const data = { msg: 'hello world', success: 'true', Details: [ { group: 'grp1', personDetails: [ { firstName: 'abc', lastName: 'xyz', mobile: 12334, state: 'abc' } ] }, { group: 'grp1', personDetails: [ { firstName: 'abc', lastName: 'xyz', mobile: 12334, state: 'abc' }, { firstName: 'abc', lastName: 'xyz', mobile: 12334, state: 'abc' } ] } ] }; const r = objectScan(['Details[*].personDetails[*]'], { rtn: 'value' })(data); console.log(r); // => [ { firstName: 'abc', lastName: 'xyz', mobile: 12334, state: 'abc' }, { firstName: 'abc', lastName: 'xyz', mobile: 12334, state: 'abc' }, { firstName: 'abc', lastName: 'xyz', mobile: 12334, state: 'abc' } ]
.as-console-wrapper {max-height: 100%;important: top: 0}
<script src="https://bundle.run/object-scan@14.0.0"></script>
免责声明:我是对象扫描的作者
尝试这个
const result = { msg: "hello world", success: "true", Details: [ { group: "grp1", personDetails: [ { firstName: "abc", lastName: "xyz", mobile: 12334, state: "abc", }, ], }, { group: "grp1", personDetails: [ { firstName: "abc", lastName: "xyz", mobile: 12334, state: "abc", }, { firstName: "abc", lastName: "xyz", mobile: 12334, state: "abc", }, ], }, ], }; const items = result.Details.map((item) => item.personDetails); console.log(items.flat());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.