简体   繁体   中英

How to add key in along with array object in node js

Here is my a resultant array and now I want to add extra key along with current key. tried . push is not a function

aa[0]['new_key'] = 'blah';    // is not working

My array is looks like.

 var aa =  [
        {
          "main": "56d940bb2b5916181d0906e2",
          "current": 6544
        }
      ]

And my original code is using mongoDB query.

connection.modal.find( { 'user_id' : user_id }, { 'abc.def' : true}, function ( err, result ) {

            if ( !err ) {

                if( result.length ) {

                    result[0]['abc'].def[0]['new_key']  = 'blah';
                    response['success'] = true;
                    response['result'] = result[0]['abc'].def;
                    response['msg'] = 'data fetch';
                    res.json(response);
                } else {

                    response['success'] = false;
                    response['result'] = '';
                    response['msg'] = 'No record found';
                    res.json(response);
                }
            } else {

                response['success'] = false;
                response['result'] = '';
                response['msg'] = 'Error';
                res.json(response);
            }
        });

I also get same problem a lot i resolved this issue by using this

connection.modal.find( { 'user_id' : user_id }, { 'abc.def' : true}, function ( err, result ) {
 /// ADD THIS LINE /////////
result = JSON.parse(JSON.stringify(result));
 ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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