Home > database >  How to iterate over all keys in a object and change the key from '_id' to 'id' b
How to iterate over all keys in a object and change the key from '_id' to 'id' b

Time:04-13

Below is the JSON file and I am trying to change the key name in offers from '_id' to 'id'

[{
        
        "offers": [{
            "i": "",
            "a": 
            "e": 25.3,
            "c": "A new concept in the ed-tech market. I can relate with the importance of the Learn By Doing philosophy. Keep up the Good Work! Definitely interested to work with you to scale the vision of the company!",
            "_id": "62565340aa2519d6cc33e791"
        }],
        "id": "62565340aa2519d6cc33e790"
    },
    {
        "er": "#3",
        "p": "Title #3",
        "p": "Idea #3",
        "at": ,
        "equity": 25.3,
        "offers": [],
        "id": "6256533baa2519d6cc33e78f"
    }
]

I am new to Node js I am able to change the 'id' key outside of every pitch but not inside 'offers' key. Can someone please help me in this.

CodePudding user response:

Try to change your code like this:

MongoClient.connect(url, function (err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var coll = dbo.collection("pitches");

  coll
    .find({})
    .sort({
      _id: -1,
    })
    .toArray(function (err, result) {
      if (err) {
        response.send(err);
      } else {
        for (const value of res) {
            for (const offer of value.offers) {
              offer.id = offer._id
              delete offer._id
            }
        }

        response.statusCode = 201;
        response.send(result);
      }
    });
});

CodePudding user response:

Your answer is almost right. Use double for loop.

let result = [
    {
        "entrepreneur": "Yakshit#4",
        "pitchTitle": "Sample Title #4",
        "pitchIdea": "Sample Idea #4",
        "askAmount": 1000000000,
        "equity": 25.3,
        "offers": [{
            "investor": "Anupam Mittal",
            "amount": 1000000000,
            "equity": 25.3,
            "comment": "A new concept in the ed-tech market. I can relate with the importance of the Learn By Doing philosophy. Keep up the Good Work! Definitely interested to work with you to scale the vision of the company!",
            "_id": "62565340aa2519d6cc33e791"
        }],
        "_id": "62565340aa2519d6cc33e790"
    },
    {
        "entrepreneur": "Yakshit#3",
        "pitchTitle": "Sample Title #3",
        "pitchIdea": "Sample Idea #3",
        "askAmount": 1000000000,
        "equity": 25.3,
        "offers": [],
        "_id": "6256533baa2519d6cc33e78f"
    }
]
for (const val of result) {
    val["id"] = val["_id"];
    delete val["_id"];
    for (const val2 of val["offers"]) {
        val2["id"] = val2["_id"];
        delete val2["_id"];
    }
}
console.log(JSON.stringify(result));


do it in mongo query

db.collection.aggregate([
  {
    $match: {}
  },
  {
    $set: {
      id: "$_id",
      offers: {
        $map: {
          input: "$offers",
          as: "o",
          in: { $mergeObjects: [ "$$o", { id: "$$o._id" } ] }
        }
      }
    }
  },
  {
    $unset: [ "_id", "offers._id" ]
  }
])

mongoplayground

CodePudding user response:

OPTION 1
as explained here You can change key name while returning query result from mongodb using aggregation.
orginal data:

{ "_id" : 2, "name" : "Sarah", "salary" : 128000 }
{ "_id" : 3, "name" : "Fritz", "salary" : 25000 }
{ "_id" : 4, "name" : "Chris", "salary" : 45000 }
{ "_id" : 5, "name" : "Beck", "salary" : 82000 }

query:

db.employees.aggregate([
  { "$project": { "employee": "$name", "salary": 1 }}
])

query result:

{ "_id" : 2, "salary" : 128000, "employee" : "Sarah" }
{ "_id" : 3, "salary" : 25000, "employee" : "Fritz" }
{ "_id" : 4, "salary" : 45000, "employee" : "Chris" }
{ "_id" : 5, "salary" : 82000, "employee" : "Beck" }

OPTION 2
you can use lodash and _.transform as explained here

  • Related