Following is my array, and I need to replace the keys name with title and Email with subtitle.
I tried some ways, but I still need to fulfill my requirement. Please provide any solution to this.
const newUpdatedList = [];
resArr.forEach((res) => {
const obj = {
title: res.name,
subtitle: res.attributes.Email
};
if (res.children) {
const newList = res.children.map((ch) => {
return {
title: ch.name,
subtitle: ch.attributes.Email,
};
});
obj.children = newList;
}
newUpdatedList.push(obj);
});
const resArr =
[ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2'
, name : 'Harsha ABC'
, custom_id : 'mani78989-1gfqv04bo'
, attributes : { Email: 'harsha#gmail.com', Role: 'admin'}
, children:
[ { user_id : 'd748037a-b445-41c2-b82f-4d6ee9396714'
, name : 'Lavaraju Allu'
, custom_id : 'mani78989-1gfqv472q'
, attributes : { Email: 'raju#gmail.com', Role: 'Manager'}
, children:
[ { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1'
, name : 'Ramesh Allu'
, custom_id : 'mani78989-1gh14i13t'
, attributes : { Email: 'ramesh#gmail.com', Role: 'Retailer'}
, children:
[ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2'
, name : 'Harsha ABC'
, custom_id : 'mani78989-1gh15nrev'
, attributes : { Email: 'harsha#gmail.com', Role: 'Delivery Manager'}
, children : []
} ] } ] }
, { user_id : '550cc296-d7e4-44fb-9d62-4c6755b3f6f2'
, name : 'Suresh Kunisetti'
, custom_id : 'mani78989-1gfqv6idi'
, attributes : { Email: 'suresh#gmail.com', Role: 'Super Admin'}
, children:
[ { user_id : '45cf19f8-36c1-4669-9333-1226c4f7b66b'
, name : 'Harish Three'
, custom_id : 'mani78989-1ggv5vffb'
, attributes : { Email: 'harish234#gmail.com', Role: 'Delivery Manager'}
, children : []
} ] }
, { user_id : '2c8535be-5fe7-40f0-892f-0f9bcffe0baa'
, name : 'Sandeep Bbb'
, custom_id : 'mani78989-1gh14m5p4'
, attributes : { Email: 'sandeep#gmail.com', Role: 'Delivery Manager'}
, children : []
}
, { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1'
, name : 'Ramesh Allu'
, custom_id : 'mani78989-1gh14pc6p'
, attributes : { Email: 'ramesh#gmail.com', Role: 'Manager'}
, children : [ ]
} ] }
]
Expected output is
const resArr =
[ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2'
, title : 'Harsha ABC'
, custom_id : 'mani78989-1gfqv04bo'
, attributes : { subtitle: 'harsha#gmail.com', Role: 'admin'}
, children:
[ { user_id : 'd748037a-b445-41c2-b82f-4d6ee9396714'
, title : 'Lavaraju Allu'
, custom_id : 'mani78989-1gfqv472q'
, attributes : { subtitle: 'raju#gmail.com', Role: 'Manager'}
, children:
[ { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1'
, title : 'Ramesh Allu'
, custom_id : 'mani78989-1gh14i13t'
, attributes : { subtitle: 'ramesh#gmail.com', Role: 'Retailer'}
, children:
[ { user_id : 'f7ba4795-d279-4c38-9a84-7a49522c50a2'
, title : 'Harsha ABC'
, custom_id : 'mani78989-1gh15nrev'
, attributes : { subtitle: 'harsha#gmail.com', Role: 'Delivery Manager'}
, children : []
} ] } ] }
, { user_id : '550cc296-d7e4-44fb-9d62-4c6755b3f6f2'
, title : 'Suresh Kunisetti'
, custom_id : 'mani78989-1gfqv6idi'
, attributes : { subtitle: 'suresh#gmail.com', Role: 'Super Admin'}
, children:
[ { user_id : '45cf19f8-36c1-4669-9333-1226c4f7b66b'
, title : 'Harish Three'
, custom_id : 'mani78989-1ggv5vffb'
, attributes : { subtitle: 'harish234#gmail.com', Role: 'Delivery Manager'}
, children : []
} ] }
, { user_id : '2c8535be-5fe7-40f0-892f-0f9bcffe0baa'
, title : 'Sandeep Bbb'
, custom_id : 'mani78989-1gh14m5p4'
, attributes : { subtitle: 'sandeep#gmail.com', Role: 'Delivery Manager'}
, children : []
}
, { user_id : '881c7731-b853-4ebc-b271-8f9e9215f7a1'
, title : 'Ramesh Allu'
, custom_id : 'mani78989-1gh14pc6p'
, attributes : { subtitle: 'ramesh#gmail.com', Role: 'Manager'}
, children : []
} ] }
]
You can use the recursive function that I created. This function is taking in an object that looks like sample_obj and then recreates the resArr where name is title and email is subtitle. Take a look:
function recursive_fix(obj) {
const sample_obj = {
user_id: obj.user_id,
title: obj.name,
custom_id: obj.custom_id,
attributes: {subtitle: obj.attributes.Email, Role: obj.attributes.Role},
children: []
};
// only adding recursive if the children array is not empty
if (obj.children.length !== 0) {
obj.children.forEach((childz) => {
sample_obj.children.push({children: [recursive_fix(childz)]})
})
}
return sample_obj
};
const newUpdatedList = [];
resArr.forEach((res) => {
newUpdatedList.push(recursive_fix(res))
})
Here's a recursive solution.
const resArr= [{"user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2","name": "Harsha ABC","custom_id": "mani78989-1gfqv04bo","attributes": {"Email": "harsha#gmail.com","Role": "admin"},"children": [{"user_id": "d748037a-b445-41c2-b82f-4d6ee9396714","name": "Lavaraju Allu","custom_id": "mani78989-1gfqv472q","attributes": {"Email": "raju#gmail.com","Role": "Manager"},"children": [{"user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1","name": "Ramesh Allu","custom_id": "mani78989-1gh14i13t","attributes": {"Email": "ramesh#gmail.com","Role": "Retailer"},"children": [{"user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2","name": "Harsha ABC","custom_id": "mani78989-1gh15nrev","attributes": {"Email": "harsha#gmail.com","Role": "Delivery Manager"},"children": []}]}]},{"user_id": "550cc296-d7e4-44fb-9d62-4c6755b3f6f2","name": "Suresh Kunisetti","custom_id": "mani78989-1gfqv6idi","attributes": {"Email": "suresh#gmail.com","Role": "Super Admin"},"children": [{"user_id": "45cf19f8-36c1-4669-9333-1226c4f7b66b","name": "Harish Three","custom_id": "mani78989-1ggv5vffb","attributes": {"Email": "harish234#gmail.com","Role": "Delivery Manager"},"children": []}]},{"user_id": "2c8535be-5fe7-40f0-892f-0f9bcffe0baa","name": "Sandeep Bbb","custom_id": "mani78989-1gh14m5p4","attributes": {"Email": "sandeep#gmail.com","Role": "Delivery Manager"},"children": []},{"user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1","name": "Ramesh Allu","custom_id": "mani78989-1gh14pc6p","attributes": {"Email": "ramesh#gmail.com","Role": "Manager"},"children": []}]}]
function changeTitles(Obj){
Obj.title = Obj.name;
Obj.attributes.subtitle = Obj.attributes.Email;
delete Obj.name;
delete Obj.attributes.Email;
if (Obj.children) {
Obj.children.forEach(changeTitles)
}
}
const clone = JSON.parse(JSON.stringify(resArr)) // Because the function mutates the object
clone.forEach(changeTitles)
console.log(clone)
I was a little late with my answer, so it looks like a copy of Brother58697's answer. The only difference is maybe the structuredClone() method, a newish global method:
const resArr= [ { "user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2", "name": "Harsha ABC", "custom_id": "mani78989-1gfqv04bo", "attributes": { "Email": "harsha#gmail.com", "Role": "admin" }, "children": [ { "user_id": "d748037a-b445-41c2-b82f-4d6ee9396714", "name": "Lavaraju Allu", "custom_id": "mani78989-1gfqv472q", "attributes": { "Email": "raju#gmail.com", "Role": "Manager" }, "children": [ { "user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1", "name": "Ramesh Allu", "custom_id": "mani78989-1gh14i13t", "attributes": { "Email": "ramesh#gmail.com", "Role": "Retailer" }, "children": [ { "user_id": "f7ba4795-d279-4c38-9a84-7a49522c50a2", "name": "Harsha ABC", "custom_id": "mani78989-1gh15nrev", "attributes": { "Email": "harsha#gmail.com", "Role": "Delivery Manager" }, "children": [] } ] } ] }, { "user_id": "550cc296-d7e4-44fb-9d62-4c6755b3f6f2", "name": "Suresh Kunisetti", "custom_id": "mani78989-1gfqv6idi", "attributes": { "Email": "suresh#gmail.com", "Role": "Super Admin" }, "children": [ { "user_id": "45cf19f8-36c1-4669-9333-1226c4f7b66b", "name": "Harish Three", "custom_id": "mani78989-1ggv5vffb", "attributes": { "Email": "harish234#gmail.com", "Role": "Delivery Manager" }, "children": [] } ] }, { "user_id": "2c8535be-5fe7-40f0-892f-0f9bcffe0baa", "name": "Sandeep Bbb", "custom_id": "mani78989-1gh14m5p4", "attributes": { "Email": "sandeep#gmail.com", "Role": "Delivery Manager" }, "children": [] }, { "user_id": "881c7731-b853-4ebc-b271-8f9e9215f7a1", "name": "Ramesh Allu", "custom_id": "mani78989-1gh14pc6p", "attributes": { "Email": "ramesh#gmail.com", "Role": "Manager" }, "children": [] } ] } ];
function trans(arr){
arr.forEach((o)=>{
o.title=o.name; delete(o.name);
o.attributes.subtitle=o.attributes.Email; delete(o.attributes.Email);
trans(o.children)
})
}
let result=structuredClone(resArr);
trans(result);
console.log(result);
I am not 100% sure I understand correctly what you're trying to do, but it seems you are trying to change the key names in an array of objects. Let me know if this is wrong. Something like this would work in that case"
const arrayOfObj = [{
name: 'value1',
email: 'value2'
}, {
name: 'value1',
email: 'value2'
}];
const newArrayOfObj = arrayOfObj.map(({
name: title,
email: subtitle,
...rest
}) => ({
title,
subtitle,
...rest
}));
console.log(newArrayOfObj);
found this answer here
A quick solution could be to stringify, string replace and parse back to object/array.
Something like this:
const asString = JSON.stringify(resArr);
const replacedNames = asString.replace(/name/g, "title");
const replacedEmail = replacedNames.replace(/Email/g, "subtitle");
const result = JSON.parse(replacedEmail);
the changed object/array is in result.
One of the Simplest way we can use is to use Object.assign something like this:
a={'name': 'xyz', 'Email': 'xyz#gmail.com'};
b= Object.assign({'title': a.name, 'subtitle': a.Email});
I am trying to remove a comment object from an array in a mongodb using the $pull operator and it seems like I have the syntax correct but it is not modifying anything.
I have looked through all the examples given on Stack to make but it still keeps responding with
{ n: 0,
nModified: 0,
opTime:
{ ts:
Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1548664023 },
t: 1 },
electionId: 7fffffff0000000000000001,
ok: 1,
operationTime:
Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1548664023 },
'$clusterTime':
{ clusterTime:
Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1548664023 },
signature: { hash: [Binary], keyId: [Long] } } }
this is the field I currently have in the DB
{
"_id" : ObjectId("5be23d8aa365d853ddfd6f15"),
"__v" : 0,
"restaurant" : {
info about restaurant
},
"comments" : [
{
"id" : "61DSLu7fFcUZ2chA8-A6HQ",
"user" : "test",
"comment" : "test"
},
{
"comment" : "testing",
"user" : "testing",
"id" : ObjectId("5c3cd3a5647f180484a5ca18")
},
{
"restaurant_id" : "61DSLu7fFcUZ2chA8-A6HQ",
"comment" : "tacos",
"name" : "test",
"user_id" : ObjectId("5c48fdf47e9ed81b08536602")
},
{
"restaurant_id" : "61DSLu7fFcUZ2chA8-A6HQ",
"comment" : "tacos",
"name" : "test",
"comm_id" : ObjectId("5c49019f8528f31b2adfb914")
},
{
"restaurant_id" : "61DSLu7fFcUZ2chA8-A6HQ",
"comment" : "hello",
"name" : "test",
"comm_id" : ObjectId("5c490237fd6e781b52f801fe")
}
],
"likes" : {
"likes" : 6
}
Currently my model shows within my restaurants model
comments: [{
restaurant_id : String,
comment : String,
name : String,
comm_id : String,
}]
the update method I have currently
db.restaurants.updateOne({restaurant_id: rest_id},
{ $pull: { comments: { $in: [{comment: "hello"}] } }
}, { safe: true })
and also have tried
db.restaurants.updateOne({restaurant_id: rest_id},
{ $pull: { comments: { $in: {"comment": "hello"} } }
}, { safe: true })
as well as
db.restaurants.updateOne({restaurant_id: rest_id},
{ $pull: { comments: { comment: "hello"} } }
}, { safe: true })
and similar variation. I can't seem to pinpoint my mistake. the response seems like it is finding the correct restaurant field, but my $pull operator just isn't working properly. Is there something wrong with my syntax or does it not work in this scenario.
Ideally, I will use the comm_id field to remove the object from the array, but I am using comment: "hello" just to test.
Is it possibly because I have different fields in the first few comments?
do it simple it will works
db.restaurants.updateOne({restaurant_id: rest_id},
{ $pull: { comments.comment: "hello"} }
}, { safe: true })
I would like the nested object with the id BAHx9KeKjuMePce6f to be updated:
{
"_id" : "sgG6G9XTvvjj7uxwQ",
"target" : [
{
"title" : "content",
"id" : "ePce6fBAHx9KeKjuM"
},
{
"title" : "content",
"id" : "BAHx9KeKjuMePce6f" <--
}
]
}
So this is what I tried:
var newData = { title: "new", one: "more", id: 'BAHx9KeKjuMePce6f' };
Collection.update(
{ _id: 'sgG6G9XTvvjj7uxwQ', 'target.id': 'BAHx9KeKjuMePce6f' },
{ $set: newData }
);
The result should be:
{
"_id" : "sgG6G9XTvvjj7uxwQ",
"target" : [
{
"title" : "content",
"id" : "ePce6fBAHx9KeKjuM"
},
{
"title": "new",
"one": "more",
"id" : "BAHx9KeKjuMePce6f"
}
]
}
In order to update specific element in array you can use mongodb positional $ operator.
Try the following query:
var newData = { title: "new", one: "more", id: 'BAHx9KeKjuMePce6f' };
Collection.update(
{ _id: 'sgG6G9XTvvjj7uxwQ', 'target.id': 'BAHx9KeKjuMePce6f' },
{ $set: { 'target.$': newData } }
);
You need the use the positional parameter $ to indicate you want to update the array element, rather than the root of the document, see the documentation:
Collection.update({
_id: 'sgG6G9XTvvjj7uxwQ',
'target.id': 'BAHx9KeKjuMePce6f'
}, {
$set: {
"target.$": newData
}
});
I have My data Stored like this on mongodb:
{
"_id" : { "$oid" : "5385a437084ea4734b03374f" },
"linea" : 1,
"egunak" : [
{
"fetxa" : "2014/05/26",
"turnoak" : [
{
"turno" : 1,
"ordenes" : [
{ "ref" : "3CI00001" },
{ "of" : "OF000d013" }
]
},
{
"turno" : 2,
"ordenes" : [
{ "ref" : "3CI00001" },
{ "of" : "112-2233" },
{ "ref" : "3CI0-0001" },
{ "ref" : "666" },
{ "ref" : "33" },
{ "ref" : "3355" },
{ "ref" : "345" },
{ "ref" : "1234" }
]
},
{
"turno" : 3,
"ordenes" : [
{ "ref" : "3CI00001" },
{ "ref" : "12" }
]
}
]
},
{ "fetxa" : "2014/05/27" },
{
"fetxa" : "2014/05/28",
"turnoak" : [
{
"turno" : 1,
"ordenes" : [
{ "ref" : "3CI0-0001" },
{ "of" : "OF200013" }
]
},
{
"turno" : 2,
"ordenes" : [
{ "ref" : "3CI00001-" },
{ "of" : "OF232233" },
{ "of" : "OF289977" }
]
},
{
"turno" : 3,
"ordenes" : [
{ "ref" : "3CI00001" },
{ "of" : "OF200-000" },
{ "ref" : "3CI00001" },
{ "of" : "OF200000" },
{ "ref" : "3CI00001" }
]
}
]
},
{ "fetxa" : "2014/05/29" },
{ "fetxa" : "2014/05/30" },
{ "fetxa" : "2014/05/31" },
{ "fetxa" : "2014/06/01" }
]
},
{
"_id" : { "$oid" : "5385a448084ea4734b033750" },
"linea" : 2,
"egunak" : [
{
"fetxa" : "2014/05/26",
"turnoak" : [
{
"turno" : 2,
"ordenes" : { "ref" : "123" }
}
]
},
{
"fetxa" : "2014/05/27",
"turnoak" : [
{
"turno" : 1,
"ordenes" : [
{ "ref" : "3CI00002" },
{ "of" : "2OF000013" }
]
},
{
"turno" : 2,
"ordenes" : [
{ "ref" : "3CI00001" },
{ "of" : "2OF2233" },
{ "ref" : "3CI00001" },
{ "ref" : "999" }
]
},
{
"turno" : 3,
"ordenes" : [
{ "ref" : "3CI00001" }
]
}
]
},
{
"fetxa" : "2014/05/28",
"turnoak" : [
{
"turno" : "2",
"ordenes" : { "ref" : "66" }
}
]
},
{
"fetxa" : "2014/05/29",
"turnoak" : [
{
"turno" : 1,
"ordenes" : [
{ "ref" : "3CI00001" },
{ "of" : "2OF200013" }
]
},
{
"turno" : 2,
"ordenes" : [
{ "ref" : "3CI00001" },
{ "of" : "2OF232233" },
{ "ref" : "3CI00001" }
]
},
{
"turno" : 3,
"ordenes" : [
{ "ref" : "3CI00001" },
{ "of" : "2OF200000" },
{ "ref" : "3CI00001" },
{ "of" : "2OF200000" },
{ "ref" : "3CI00001" }
]
}
]
},
{ "fetxa" : "2014/05/30" },
{ "fetxa" : "2014/05/31" },
{ "fetxa" : "2014/06/01" }
]
}
Now I want to find into my data between two dates but the data is stored with in string, how can I achieve that? or I need to store my data on date format?
This is my persist function on nodejs:
exports.save = function(req, res){
db.open(function(err, db) {
if(!err) {
var data = req.body;
var BSON = mongo.BSONPure;
var o_id = new BSON.ObjectID(data._id);
db.collection('test').update({'_id': o_id}, { $set :{ egunak: data.egunak } }, {safe:true, multi:false, upsert:false}, function(e, result){
if (e) console.log(e)
res.send((result===1)?{msg:'success'}:{msg:'error'})
})
} else {
onErr(err, function(){
console.log(err);
});
}
});
};
Where the $set value is my JSON. How can I store the date data?
You can alway use
JSON.stringify(js_object); // this convert js Object to object in string format
before sending data, and
JSON.parse(object_in_string_format); // this convert back the object in string format to js object.
after received the data. Read more at Mozilla MDN.
You should store datetime in Date type
Then you can 'select' like the following:
db.collection('Datuak').find(
{"egunak.fetxa": {"$gte": new Date(1979, 1, 1), //date type here
"$lt": new Date(2222, 12, 31)}
}
)
Though it is better you store your dates in DATE format, but if you still want a workaround you can use Date.parse(date) function to get the value in milliseconds. I tried following in mongodb 2.4.8 and both works well
var d = Date.parse("March 21, 2012");
var d = Date.parse("2014/03/21");
now 'd' will contain data in milliseconds and you can use that to find data between two dates.