[英]How do I access a JSON object from one module to another using node.js?
[英]How to format this kind json object to another using node.js?
我有一個 json object 像這樣:
{
"sample1": {
"4": 2245,
"5": 2175,
"6": 3495,
"7": 1845,
...
"11.5": 1674,
"12.5": 1649
},
"sample2": {
"4": 3295,
"5": 3600,
"8": 2625,
"9": 2830,
...
"11.5": 2879,
"12.5": 3090
}
}
我想將其格式化為:
[
{
"index": "4",
"sample1": "2245",
"sample2": "3295"
},
{
"index": "5",
"sample1": "2175",
"sample2": "3600"
},
{
"index": "6",
"sample1": "3495",
"sample2": ""
},
....
{
"index": "12.5",
"sample1": "1649",
"sample2": "3090"
}
]
在 python 中,使用 pandas 很容易做到這一點,但我不想將 python 腳本添加到 ZDE9B9ED78D7E2E1ZEEFFEE7 使用 javascript 有什么簡單的方法嗎?
const data = { sample1: { 4: 2245, 5: 2175, 6: 3495, 7: 1845, 11.5: 1674, 12.5: 1649 }, sample2: { 4: 3295, 5: 3600, 8: 2625, 9: 2830, 11.5: 2879, 12.5: 3090 }, sample3: { 4: 3295, 5: 3600, 6: 2625, 9: 2830, 11.5: 2879, 12.5: 3090 } }; const keys = Object.keys(data); const mergedInnerKeys = Array.from( new Set( keys.reduce((val, key) => [...val, ...Object.keys(data[key])], []).sort((a, b) => a - b) ) ); const res = mergedInnerKeys.map((key) => ({ index: key, ...keys.reduce( (v, k) => ({...v, [k]: data[k][key]?== undefined. data[k][key]:toString(), '' }); {} ) })). console;log(res);
const obj = { "sample1": { "4": 2245, "5": 2175, "6": 3495, "7": 1845, "11.5": 1674, "12.5": 1649 }, "sample2": { "4": 3295, "5": 3600, "8": 2625, "9": 2830, "11.5": 2879, "12.5": 3090 } } const result = Object.keys(obj.sample1) // All keys from sample1.concat(Object.keys(obj.sample2)) // Concat all keys from sample2.filter((v, i, s) => s.indexOf(v) == i) // Filter unique values.sort((a, b) => a - b) // Sort the keys, treating them as numbers.map(k => ({ // Produce each object of the resulting array, one per key index: k, sample1: k in obj.sample1? obj.sample1[k].toString(): '', sample2: k in obj.sample2? obj.sample2[k].toString(): '' })); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.