push to mongodb array using dynamic key - javascript

I'm trying to push a data by dynamic key
db structure:
{
"obj1":{
"array":[
{
"field1":"text1"
},
{
"field2":"text2"
}
]
},
"id":123;
},
{
"obj2":{
"array":[
{
"field1":"text1"
},
{
"field2":"text2"
}
]
},
"id":1234;
}
I'm trying to use variable as a key in map path:
var a = 'obj2';
db.collection('fooCollection').update({'id':1234},{$push:{a.array:{ "field3":"text3"}}});
if I do:
db.collection('fooCollection').update({'id':1234},{$push:{"obj2.array":{ "field3":"text3"}}});
it works, but I badly need to use dynamic key.

That can't be done with object literals. Try this:
var a = 'obj2';
var pushObj = {};
pushObj[a + '.array'] = { "field3": "text3" };
db.collection('fooCollection').update({ 'id':1234 }, { $push: pushObj });

Related

How to add dynamic elements to an object in typescript

I am sorry if I am asking a very basic question, I have done some research over the internet but not getting anything useful.
I have a typescript object like :
var productIds=["one","two","three"];
let searchfilter = {
or: [{
id: { match:productids['0'] }
},{
id: { match:productids['1'] }
},{
id: { match:productids['2'] }
}]
};
My productIds can be dynamic and may hold different counts of values.
How can I create the same structure for a dynamic number of values. I tried forEach, but not sure about the syntax.
productids.forEach(function(value){
// not sure if this is right syntax, I am not getting desired results.
searchfilter.or = { id: { match:value }};
});
Can you help me with it?
You can create your full or array with a simple .map() :
var productIds = ["1", "2", "3"];
let searchfilter = {
or : productIds.map( n => ({ id : { match : productIds[n] } }))
};
However Mongo (which I believe you are using) has a $match method that's made to match a list :
{
$match: {
productIds: {
$in: productIds
}
}
}
I'll keep it as simple as I can
var productIds=["one","two","three"];
let searchfilter = productIds.map(p => {
return {id: { match: p }};
});
// function
addNewProduct(id: string) {
this.searchfilter.push({id: { match: id }});
}

Retrieve each value from a specific key with json

I would like to know if there is a way to get every values of "-temp" from the .json
{
"weather":{
"notes":{
"cities":[
{
"-id":"scranton",
"-temp":"17"
},
{
"-id":"paris",
"-temp":"16"
},
{
"-id":"new york",
"-temp":"18"
}
]
}
}
}
How I tried to get it with JavaScript but that didn't work and I get undefined
data.weather.notes.cities['-temp']
How can I get every value of "-temp"?
You can use map:
const temps = data.weather.notes.cities.map(city => city["-temp"]);
console.log(temps); // ["17", "16", "18"]
Of course you can always access to them individually:
const { cities } = data.weather.notes;
console.log(cities[0]["-temp"]); // "17"
Or loop all of them:
for (let city of cities) {
console.log("temperature in %s is %s°",
city["-id"], city["-temp"]
);
}
You could possibly iterate through all the cities and gather the "-temp" keys.
data.weather.notes.cities.forEach(function(element) {
for (var em in element) {
if (em == "-temp")
{
console.log(element[em])
}
}
});
#ZER0 answer is probably the best though.
var data = {
"weather":{
"notes":{
"cities":[
{
"-id":"scranton",
"-temp":"17"
},
{
"-id":"paris",
"-temp":"16"
},
{
"-id":"new york",
"-temp":"18"
}
]
}
}
};
for(var i in data.weather.notes.cities) {
let city = data.weather.notes.cities[i];
console.log(city["-temp"]); //You_ can get it here
}
You can't use JSON the same way you use jquery selectors. In your case, you need to map your array of cities.
const object = {
"weather":{
"notes":{
"cities":[
{
"-id":"scranton",
"-temp":"17"
},
{
"-id":"paris",
"-temp":"16"
},
{
"-id":"new york",
"-temp":"18"
}
]
}
}
};
const tempList = object.weather.notes.cities.map(city => city['-temp']);
//result: ["17", "16", "18"]
See map documentation for further information.

I am trying to check if given value exist as key in array of objects

I am trying to check if given value exist as key in array of objects
var obj = [{
tapCount1: '10'
}, {
tapCount2: '500'
}, {
tapCount3: '1250'
}, {
tapCount4: '1250'
}, {
wtOfSample: '41.00'
}, {
initialVolume: '66.0'
}, {
tapCountvol1: '60.0'
}, {
tapCountvol2: '53.0'
}, {
tapCountvol3: '52.0'
}, {
tapDensity: '0.788'
}, {
compressibilityIndex: '21.212'
}, {
hausnerRatio: '1.269'
}];
i had use below code
if (arrTDTData.hasOwnProperty("tapCount1") == false) {
count1 = 0;
} else {
count1 = arrTDTData.tapCount1;
}
i want to check if key is equal tapCount1 then it will return true else flase```
If you want to check if there is an object in the array that has tapCount1 key, you can use some().
The some() method tests whether at least one element in the array
passes the test implemented by the provided function. It returns a
Boolean value.
var obj = [{"tapCount1":"10"},{"tapCount2":"500"},{"tapCount3":"1250"},{"tapCount4":"1250"},{"wtOfSample":"41.00"},{"initialVolume":"66.0"},{"tapCountvol1":"60.0"},{"tapCountvol2":"53.0"},{"tapCountvol3":"52.0"},{"tapDensity":"0.788"},{"compressibilityIndex":"21.212"},{"hausnerRatio":"1.269"}];
var result = obj.some(o => "tapCount1" in o);
console.log(result);
Use includes with map and Object.keys (and reduce to flatten the array):
var obj = [{tapCount1:'10'},{tapCount2:'500'},{tapCount3:'1250'},{tapCount4:'1250'},{wtOfSample:'41.00'},{initialVolume:'66.0'},{tapCountvol1:'60.0'},{tapCountvol2:'53.0'},{tapCountvol3:'52.0'},{tapDensity:'0.788'},{compressibilityIndex:'21.212'},{hausnerRatio:'1.269'}];
const res = obj.map(Object.keys).reduce((acc, curr) => acc.concat(curr)).includes("tapCount1");
console.log(res);
You can also use some on the array itself with hasOwnProperty (to avoid scanning the prototype):
var obj = [{tapCount1:'10'},{tapCount2:'500'},{tapCount3:'1250'},{tapCount4:'1250'},{wtOfSample:'41.00'},{initialVolume:'66.0'},{tapCountvol1:'60.0'},{tapCountvol2:'53.0'},{tapCountvol3:'52.0'},{tapDensity:'0.788'},{compressibilityIndex:'21.212'},{hausnerRatio:'1.269'}];
const res = obj.some(e => e.hasOwnProperty("tapCount1"));
console.log(res);
You could get a single object and check the wanted property.
var array = [{ tapCount1: '10' }, { tapCount2: '500' }, { tapCount3: '1250' }, { tapCount4: '1250' }, { wtOfSample: '41.00' }, { initialVolume: '66.0' }, { tapCountvol1: '60.0' }, { tapCountvol2: '53.0' }, { tapCountvol3: '52.0' }, { tapDensity: '0.788' }, { compressibilityIndex: '21.212' }, { hausnerRatio: '1.269' }],
tapCount1 = 'tapCount1' in Object.assign({}, ...array);
console.log(tapCount1);

How to add attribute to the root of JSON object consists of array of objects?

How to add attribute to the root of JSON object consists of array of objects?
If my JSON object something like that:
[
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
]
I do the following:
worktimeJSON.Id = $('.Js-WorkTime-id').val();
worktimeJSON.Name = $('.Js-WorkTime-name').val();
worktimeJSON.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
And make sure that the jQuery fetching data from the inputs but this doesn't work.
This will change property of all object in array if you want to change in particular then use index for this for exp->
worktimeJSON[0].Id = $('.Js-WorkTime-id').val();
worktimeJSON[0].Name = $('.Js-WorkTime-name').val();
worktimeJSON[0].NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
var worktimeJSON = [
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
];
worktimeJSON = worktimeJSON.map(function(val){
val.Id = $('.Js-WorkTime-id').val();
val.Name = $('.Js-WorkTime-name').val();
val.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
return val;
});
Push can do the job.
let worktimeJSON = [
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
];
worktimeJSON.push
({
id: "someID",
name: "toto",
WorkTimeRegulationId: 42
});
console.log(worktimeJSON);
I structure my object like this:
let WorkTimeRegulationViewModelJSON = {
Id: $('.Js-WorkTimeRegulation-id').val(),
Name: $('.Js-WorkTimeRegulation-name').val(),
NumberOfAvailableRotations: $('.Js-WorkTimeRegulation-rotations').val(),
AssignedWorkTimes: JSON.parse(worktimeJSON)
};

Cannot read property 'concat' of undefined

to begin with, I have a multilevel of entities as in
country unit ----> customer reporting group ----> customers
each country unit has different customer reporting groups and each of the later has different customers
in the code the variable names are
cu ----> crg ---> customer
this is represented in a multilevel object called menuData:
menuData = {
cu1: {
CRG3: {
Customer1: {},
Customer5: {}
},
CRG7: {
Customer3: {},
Customer2: {},
Customer7: {}
}
},
cu4: {
CRG1: {
Customer2: {},
Customer4: {}
},
CRG3: {
Customer4: {}
}
}
};
what I wanted to do is to construct unique id for each level in a multilevel objects as well as in for example the ids for the customer units will be the same
cu1 and cu2 and so on
for the customer reporting groups the ids will consist of the cu + the crg as in
cu1+crg4
for the customer:
cu1+crg4+customer6;
what I did is a function called getIds
var getIds = function(menuData) {
var ids = {};
for (cu in menuData) {
ids[cu] = cu;
for (crg in menuData[cu]) {
if (!(ids[cu] in ids)) {
ids[cu] = {};
ids[cu][crg] = ids[cu].concat(crg);
} else ids[cu][crg] = ids[cu].concat(crg);
for (customer in menuData[cu][crg]) {
if (!ids[cu][crg]) {
ids[cu][crg] = {};
ids[cu][crg][customer] = ids[cu][crg].concat(customer);
} else ids[cu][crg][customer] = ids[cu][crg].concat(customer);
}
}
}
console.log(ids);
return ids;
};
the error I got is
Cannot read property 'concat' of undefined
what I have tried is that, because it says that it's undefined, I try to define it if its not already defined as in
if (!(ids[cu] in ids)) {
ids[cu] = {};
ids[cu][crg] = ids[cu].concat(crg);
}
if its not defined, define it and insert the value, but if its defined, only assign the value
else ids[cu][crg] = ids[cu].concat (crg );
why do I get this error? and how to get the the ids in multilevel objects ?
edit, excpected output is
ids = {
"cu1": {
"cu1+CRG3": { "cu1+CRG3+Customer1":{}, "cu1+CRG3+Customer5":{} },
"cu1+CRG7": { "cu1+CRG7+Customer3":{}, "cu1+CRG7+Customer2":{}, "cu1+CRG7+Customer7":{} }
},
"cu4": {
"cu4+CRG1": { "cu4+CRG1+Customer2":{}, "cu4+CRG1+Customer4":{} },
"cu4+CRG3": { "cu4+CRG3+Customer4":{}}
}
}
The Problem with your Code is that you are using Objects to store your data and Objects don´t have the Method "concat" only Arrays have the "concat" Method. Your Object must look like these to work:
menuData = [
"cu1": [
"CRG3": [ "Customer1":{}, "Customer5":{} ],
"CRG7": [ "Customer3":{}, "Customer2":{}, "Customer7":{} ]
],
"cu4": [
"CRG1": [ "Customer2":{}, "Customer4":{} ],
"CRG3": [ "Customer4":{}]
]
]
Here´s a reference : MDN Array.concat()
What can be confusing in JS is that an Object Property can be accessed like an Array.
Update after Expected Output was added:
okay than i think concat is not the right solution for your Problem.
Try it with something like this:
var ids = {};
var menuData = {
cu1: {
CRG3: {
Customer1: {},
Customer5: {}
},
CRG7: {
Customer3: {},
Customer2: {},
Customer7: {}
}
},
cu4: {
CRG1: {
Customer2: {},
Customer4: {}
},
CRG3: {
Customer4: {}
}
}
};
for (propKeyLevel1 in menuData){
ids[propKeyLevel1] = {};
var propLevel1 = ids[propKeyLevel1];
for(propKeyLevel2 in menuData[propKeyLevel1]){
propLevel1[propKeyLevel1+"+"+propKeyLevel2] = {};
var propLevel2 = propLevel1[propKeyLevel1+"+"+propKeyLevel2];
for(propKeyLevel3 in menuData[propKeyLevel1][propKeyLevel2]){
propLevel2[propKeyLevel1+"+"+propKeyLevel2+"+"+propKeyLevel3] = {};
}
}
}
console.log(ids);
concat is a method for for a String or an Array, here you call it on an object hence the error.
What you're trying to do is a bit unclear to me, but maybe you could try that :
ids[cu][crg] = crg;
instead of :
ids[cu][crg] = ids[cu].concat (crg );
Because that's what you seem to be trying.
I’d try it this way:
function getIds(dataIn, idsIn) {
idsIn = idsIn || [];
var dataOut = {}, idOut;
for (var idIn in dataIn) {
idsOut = idsIn.concat([idIn]);
dataOut[idsOut.join('+')] = getIds(dataIn[idIn], idsOut);
}
return dataOut;
}
Perfect use case for a recursive function passing down an array (idsOut) of the ids of the previous layers to generate the intended object keys. Pretty straight forward.

Categories

Resources