arrays - 如何将 Node js中的格式数组从1个字符串更改为另一个对象

标签 arrays node.js json concatenation

我有一个像这样的 json :

{
    "status": 1,
    "message": "ok",
    "data": [
        {
            "tenor": "23"
        },
        {
            "tenor": "17"
        },
        {
            "tenor": "37"
        },
        {
            "tenor": "27,29"
        },
        {
            "tenor": "33,35"
        }
    ]
}

我希望结果是这样的:

{ "status": 1, "message": "ok", "data": [ { "tenor": "23" }, { "tenor": "17" }, { "tenor": "37" }, { "tenor": "27" }, { "tenor": "29" }, { "tenor": "33" }, { "tenor": "35" } ] }

我尝试过的:

var arrayCoba = [];
var array1 = { "status": 1, "message": "ok", "data": [ { "tenor": "23" }, { "tenor": "17" }, { "tenor": "37" }, { "tenor": "27,29" }, { "tenor": "33,35" } ] }

for(var i = 0; i<array1.data.length; i++){
    var string = array1.data[i].tenor;
    var substring = ",";

    if(string.includes(substring) == true){
        var tenor = array.data[i].tenor;
        var tenorArr = tenor.split(',');
        var dataTenor = tenorArr.map(tenor => ({ tenor }));
        arrayCoba.push(dataTenor);
    }
 }

 var dataHasil = array1.data.concat(arrayCoba);

 return res.json({status:1,message:'ok',data:dataHasil}); 

但我得到的结果是:

{
    "status": 1,
    "message": "ok",
    "data": [
        {
            "tenor": "23"
        },
        {
            "tenor": "17"
        },
        {
            "tenor": "37"
        },
        {
            "tenor": "27,29"
        },
        {
            "tenor": "33,35"
        },
        [
            {
                "tenor": "27"
            },
            {
                "tenor": "29"
            }
        ],
        [
            {
                "tenor": "33"
            },
            {
                "tenor": "35"
            }
        ]
    ]
}

有人能帮我吗?谢谢..

最佳答案

var dataTenor = tenorArr.map(tenor => ({ tenor })); 返回一个 tenor 对象数组。 arrayCoba.push(dataTenor); 将数组添加到其他数组中,为此您将在数组中获得一个数组。

使用spread operator -> arrayCoba.push(...dataTenor);

for (var i = 0; i < array1.data.length; i++) {
    var string = array1.data[i].tenor;
    var substring = ",";

    if (string.includes(substring) == true) {
        var tenor = array1.data[i].tenor;
        var tenorArr = tenor.split(',');
        var dataTenor = tenorArr.map(tenor => ({
            tenor
        }));
        arrayCoba.push(...dataTenor);
    } else {
        arrayCoba.push(array1.data[i]);
    }
}

var dataHasil = arrayCoba;

更新:使用 map 运算符的另一种方式。

var substring = ',';

var copyDataTenors = array1.data;
var arrayCoba = "".concat(copyDataTenors
    .map(obj => obj.tenor))
    .split(substring)
    .map(tenorString => ({
        'tenor': tenorString
    }))

var dataHasil = arrayCoba;

更新:与以前的解决方案相比,具有递归更通用

const data = [{
        "tenor": "23"
    },
    {
        "tenor": "17"
    },
    {
        "tenor": "37"
    },
    {
        "tenor": "27,29"
    },
    {
        "tenor": "33,35"
    }
]

/**
 *
 * @param {*} fn function callback
 * @param {*} v string[] or string
 * @param {*} attr string
 * @param {*} substring string
 */
const processDeepObject = (fn, v, attr, substring) => {
    return typeof v === 'string' ? {
        [attr]: v
    } : v[attr] ? fn(v[attr].split(substring), attr, substring) : [];
}

/**
 * Version 1
 * @param {*} arr Array of objects
 * @param {*} attr target you want keep (for this use case tenor)
 * @param {*} substring which char to split the data (for this use case ',')
 */
const deepObjectFlatten = (arr, attr, substring) => [].concat(...arr.map((v) => processDeepObject(deepObjectFlatten, v, attr, substring)));



/**
 * Version 2 same as version 1 but compact
 * @param {*} arr Array of objects
 * @param {*} attr target you want keep (for this use case tenor)
 * @param {*} substring which char to split the data (for this use case ',')
 */
const deepObjectFlattenV2 = (arr, attr, substring) => [].concat(...arr.map((v) => {
    return typeof v === 'string' ? {
        [attr]: v
    } : v[attr] ? deepObjectFlattenV2(v[attr].split(substring), attr, substring) : [];
}));


console.log(deepObjectFlatten(data, 'tenor', ','))
console.log(deepObjectFlattenV2(data, 'tenor', ','))
/*
Output :
//v1
[ { tenor: '23' },
  { tenor: '17' },
  { tenor: '37' },
  { tenor: '27' },
  { tenor: '29' },
  { tenor: '33' },
  { tenor: '35' } ]

//v2
  [ { tenor: '23' },
  { tenor: '17' },
  { tenor: '37' },
  { tenor: '27' },
  { tenor: '29' },
  { tenor: '33' },
  { tenor: '35' } ]
 */

关于arrays - 如何将 Node js中的格式数组从1个字符串更改为另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58011187/

相关文章:

windows - 在 Windows 7 上使用 Node 0.12.2 和 npm 2.7.4 ionic 安装错误

node.js - eslint:忽略模式规则不起作用

php - 使用 jQuery/JS 读取 JSON 数组

javascript - 如何获取指向javascript对象属性的链接数

php - 优化我的循环以返回而不是执行 10 次查询

javascript - 考虑到 rowspan 和 colspan,如何从一维数组创建动态 html 表?

python - 如何使用 numpy loadtxt 加载多列?

python - 检查 2 列表中有多少值相等

javascript - 无法使用 dynamodb-data-mapper-js 通过 LSI 创建 DynamoDB 表

javascript - json 函数在 vs 2010 中未执行