javascript - 如何通过 Node.js 或 NPM 模块组合/序列化此类 JSON 对象?

标签 javascript node.js json serialization node-modules

如果有人建议如何获得这样的 JSON,我将不胜感激

[
  {
    "type": "A_TYPE",
    "value": "foo"
  },
  {
    "type": "A_TYPE",
    "value": "bar"
  },
  {
    "type": "B_TYPE",
    "value": "qux"
  },
  {
    "type": "C_TYPE",
    "value": [
      10000,
      19999
    ],
    "name": "1xxxx"
  }
]

来自这样一个JSON

[
  {
    "type": "A_TYPE",
    "value": [
      "foo",
      "bar"
    ]
  },
  {
    "type": "B_TYPE",
    "value": [
      "qux"
    ]
  },
  {
    "type": "C_TYPE",
    "value": [
      [
        10000,
        19999
      ]
    ]
  }
]

在这种情况下,具有类似"type":"A_TYPE" 的属性的对象(您要在其中组合"value":"")可以是多个.

预先感谢您的帮助!

最佳答案

我针对您的问题做了这个解决方案。

let arr = [
  {
    "type": "A_TYPE",
    "value": [
      "foo",
      "bar"
    ]
  },
  {
    "type": "B_TYPE",
    "value": [
      "qux"
    ]
  },
  {
    "type": "C_TYPE",
    "value": [
      [
        10000,
        19999
      ]
    ]
  }
];

let newArr = [];

for (let i = 0; i < arr.length; i++) {
  for (let j = 0; j < arr[i].value.length; j++) {
    let value = arr[i].value[j]; // Get value from the object
    let type = arr[i].type;  // Get type from the object

    // New Object to push to the new Array
    let tempObj = {};
    tempObj.type = type;
    tempObj.value = value;
    newArr.push(tempObj);  // Push object to array
  }
}


console.log(JSON.stringify(newArr));

Test it here

关于javascript - 如何通过 Node.js 或 NPM 模块组合/序列化此类 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58080327/

相关文章:

windows - Windows 上的 Node.js 和文件系统 - EBUSY 错误

json - Golang-解析嵌套的json值

json - 根据术语过滤器列表,Elastic Search术语聚合无法正常工作

javascript - 在 Yii2 中使用 Clipboard.js

javascript - 将插件应用到 DOM 中的新元素 (jquery)

node.js - 使用 2 个字段的 Mongoose 自定义验证

node.js - amazon-s3 上传因循环上传文件而失败

javascript - 谷歌图表 JSON

javascript - 居中和裁剪 img 标签

php - PHP 中的 MongoDate 结构 - JSON 输出