使用节点js将嵌套的json值推送到数组

时间:2019-10-18 11:41:47

标签: arrays node.js json couchbase

我需要将json结果显示为嵌套数组格式:

{
    "state": [
        {
            "stateName": "tamilnadu"
        }
    ],
     "city": [
        {
            "cityName": "chennai"
        }
    ]
}

这是我的代码。我是节点开发的新手

exports.stateId = function (req, res) {
    state.find(req.body.countryId,  function() {
        var query = N1qlQuery.fromString('SELECT stateId,stateName FROM travel _type='state'');

        myBucket.query(query, async function(err, result) {
            var state=[];
        await result.forEach(ele => {
        var item= {
            stateName:ele.stateName
        }
        if(ele.stateName != undefined)

        state.push(item);
    });

    res.send({state});
 });
 });
};


exports.cityId = function (req, res) {
    city.find(req.body.stateId,  function() {
        var query = N1qlQuery.fromString('SELECT cityId,cityName FROM travel where _type="city"');
        myCluster.query(query, async function(err, result) {
            var city=[];
        await result.forEach(ele => {
        var item= {
            cityName:ele.cityName
        }
        if(ele.cityName != undefined)

        city.push(item);
    });
    res.send({city});
 });
 });
};

目前,我将获得类似于两个不同数组的结果。我需要将json结果合并到单个嵌套数据中

1 个答案:

答案 0 :(得分:1)

如果您具有以下数据:

const data_1 =
{
  "state": [
    { "stateName": "tamilnadu" }
  ]
};
const data_2 =
{
  "city": [
    { "cityName": "chennai" } ]
};

您想要的对象是:

{
    "state": [
        {
            "stateName": "tamilnadu"
        }
    ],
     "city": [
        {
            "cityName": "chennai"
        }
    ]
}

然后您可以使用Object.assign方法:

let desired = Object.assign({}, data_1, data_2);
console.log(`desired: `, desired)