繁体   English   中英

如何使用 node.js 将这种 json object 格式化为另一个?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM