最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

在Node.js中将2级JSON转换为多个1级JSON

IT培训 admin 4浏览 0评论

在Node.js中将2级JSON转换为多个1级JSON

我在节点中编写一个通用函数会遇到问题,它会解析JSON,如下所示:

{
    "parserId": 1,
    "filters": [
        {
            "filterName": "replaceTitle",
            "regex": "..."
        },
        {
            "filterName": "replaceRegion",
            "regex": "..."
        }
]}

像这样的多个JSON:

{ "parserId": 1, "filterName": "replaceTitle","regex": "..." },{ "parserId": 1, "filterName": "replaceRegion", "regex": "..."}

如果这个函数是通用的,那将是很好的,所以无论JSON中的字段名称是什么,只要它以相同的方式构建。是否有任何节点包已经在做呢?谢谢您的帮助!

回答如下:

您可以映射数组的每个项目,并使用parserId附加一个带有数组项目的对象。

var object = { parserId: 1, filters: [{ filterName: "replaceTitle", regex: "..." }, { filterName: "replaceRegion", regex: "..." }] },
    array = object.filters.map(o => Object.assign({ parserId: object.parserId }, o));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

在Node.js中将2级JSON转换为多个1级JSON

我在节点中编写一个通用函数会遇到问题,它会解析JSON,如下所示:

{
    "parserId": 1,
    "filters": [
        {
            "filterName": "replaceTitle",
            "regex": "..."
        },
        {
            "filterName": "replaceRegion",
            "regex": "..."
        }
]}

像这样的多个JSON:

{ "parserId": 1, "filterName": "replaceTitle","regex": "..." },{ "parserId": 1, "filterName": "replaceRegion", "regex": "..."}

如果这个函数是通用的,那将是很好的,所以无论JSON中的字段名称是什么,只要它以相同的方式构建。是否有任何节点包已经在做呢?谢谢您的帮助!

回答如下:

您可以映射数组的每个项目,并使用parserId附加一个带有数组项目的对象。

var object = { parserId: 1, filters: [{ filterName: "replaceTitle", regex: "..." }, { filterName: "replaceRegion", regex: "..." }] },
    array = object.filters.map(o => Object.assign({ parserId: object.parserId }, o));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
发布评论

评论列表 (0)

  1. 暂无评论