Merge X-numbers of JSON into one JavaScript Object - javascript

I have several Ajax-requests that retrieves data from the server...
I want to add them together, so I can use the data set later.
This is how one JSON-looks like:
{
"51" : { id:"51", name:"frank" },
"52" : { id:"52", name:"jonny" }
}
A second later there might come another one, with the exactly the same structure. How do I just "append" a new json into this to make a large object with the same structure..
EG: (append like this)
{
"51" : { id:"51", name:"frank" },
"52" : { id:"52", name:"jonny" },
"72" : { id:"72", name:"daniel"},
"73" : { id:"73", name:"lisa"},
"74" : { id:"74", name:"ida"},
"75" : { id:"75", name:"ali"}
}

Assuming that the ID will always be unique, you can do something like:
var buffer = {};
messageSource.on('message', function (msg) {
var msgKeys = Object.keys(msg); // Get the list of IDs
msgKeys.forEach(function (key) { // For each numeric key...
buffer[key] = msg[key]; // Copy the message
});
});
If you cannot guarantee unique IDs, you'll need some minor changes:
var buffer = {};
messageSource.on('message', function (msg) {
var msgKeys = Object.keys(msg);
msgKeys.forEach(function (key) {
buffer[key] = (buffer[key] || []).push(msg[key]); // Only change, append to list for that key
});
});

You should use Jquery $.merge:
var obj1 = {
"51" : { id:"51", name:"frank" },
"52" : { id:"52", name:"jonny" }
};
var obj2 = {
"72" : { id:"72", name:"daniel"},
"73" : { id:"73", name:"lisa"},
"74" : { id:"74", name:"ida"},
"75" : { id:"75", name:"ali"}
}
var result = $.extend(obj1, obj2);
Working exemple here

Related

Merge Multiple Objects (es5)

I have a requirement to merge two (or Multiple) Objects as a single object. While keeping each Object name as the parent key.
var event =
{ id : '45243'
, name : 'Cardiff locè'
, loc : 'Cardiff'
}
var alert =
{ node : 'sdwan edge'
, severity : 'critical'
}
The output should be like this:
var mergedObject =
{ event :
{ id : '45243'
, name : 'Cardiff loc'
, loc : 'Cardiff'
}
, alert:
{ node : 'sdwan edge'
, severity : 'critical'
}
}
mergeObject.event = event;
mergeObject.alert = alert;
That's not really merging. The existing objects are unchanged. You are just creating a new object.
var mergedObject = {
"event": event,
"alert": alert
};
var event = {
"id": "45243",
"name": "Cardiff loc",
"loc": "Cardiff"
}
var alert = {
"node": "sdwan edge",
"severity": "critical"
}
var mergedObject = {
event,
alert
};
console.log(mergedObject)

JavaScript - Targeting an object value to create another variable

So I have an array which looks like this:
[
{ TransactionValues: '50.00' },
{ TransactionValues: '-77.43' },
{ TransactionValues: '-20.23' },
{ TransactionValues: '200.23' }
]
I am trying to find a way to target the monetary value and create a variable based on the sum of these. When I try to target the "50.00" for example I get "Undefined" and it's still an array.
I'm not exactly sure how I can target it specifically, is it possible? Any help would be appreciated
As per the comments here is the full code (be wary I'm still learning so it's not elegant):
var fs = require('fs');
var parse = require('csv-parse');
var transactionValues = []; //Need an array to hold transactions
var currentTrans = [];
var savingsTrans = [];
//constuctor for transactions
function addData (id, accountType, initiatorType, dateTime, transactions) {
var data = {
"AccountID" : id,
"AccountType" : accountType,
"InitiatorType" : initiatorType,
"DateTime" : dateTime,
"TransactionValues" : transactions
}
transactionValues.push(data); //should add a new line
}
function logTrans (accountType, transactions) {
if (accountType == "CURRENT") {
var cTrans = {
"TransactionValues" : transactions
}
currentTrans.push(cTrans);
}
else {
var sTrans = {
"TransactionValues" : transactions
}
savingsTrans.push(sTrans);
}
};
//parses the csv file, loops each row and adds it to the transactionValue array
var parser = parse({columns: true}, function (err, results) {
console.table(results);
for (const row of results) {
addData(row.AccountID, row.AccountType, row.InitiatorType, row.DateTime, row.TransactionValue );
logTrans(row.AccountType, row.TransactionValue);
}
console.log(transactionValues);
console.log(currentTrans);
console.log(savingsTrans);
});
fs.createReadStream(__dirname+'/testData/customer-1234567-ledger.csv').pipe(parser)
not completely following but at the end of the day you have an array like data below.
you can use filter to target the attribute you want.
you can use map to pull out just the values.
you can use reduce to sum them all up.
run the snippet below to see each step
const data = [
{ TransactionValues: '50.00', AccountType: 'CURRENT' },
{ TransactionValues: '-77.43', AccountType: null},
{ TransactionValues: '-20.23', AccountType: 'CURRENT' },
{ TransactionValues: '200.23', AccountType: null }
];
const CurrentTrans = data.filter((x) => x.AccountType === 'CURRENT');
const SavingTrans = data.filter((x) => x.AccountType !== 'CURRENT');
console.log('CurrentTrans');
console.log(CurrentTrans);
console.log('SavingTrans');
console.log(SavingTrans);
const CurrentTransValues = CurrentTrans.map((x) => parseFloat(x.TransactionValues));
const SavingTransValues = SavingTrans.map((x) => parseFloat(x.TransactionValues));
console.log('CurrentTransValues');
console.log(CurrentTransValues);
console.log('SavingTransValues');
console.log(SavingTransValues);
const TotalCurrentValues = CurrentTransValues.reduce((sum, x) => sum + x);
const TotalSavingValues = SavingTransValues.reduce((sum, x) => sum + x);
console.log('TotalCurrentValues');
console.log(TotalCurrentValues.toFixed(2));
console.log('TotalSavingValues');
console.log(TotalSavingValues.toFixed(2));
So I may have fixed it by using parseFloat in my addData and logTrans functions:
function addData (id, accountType, initiatorType, dateTime, transactions) {
var data = {
"AccountID" : id,
"AccountType" : accountType,
"InitiatorType" : initiatorType,
"DateTime" : dateTime,
"TransactionValues" : parseFloat(transactions)
}
transactionValues.push(data); //should add a new line
}
function logTrans (accountType, transactions) {
if (accountType == "CURRENT") {
var cTrans = parseFloat(transactions);
currentTrans.push(cTrans);
}
else {
var sTrans = parseFloat(transactions);
savingsTrans.push(sTrans);
}
};
Now that seems to of worked. So I can use the "Sum values of objects in array" as suggested before. Thank you everyone :)

Add conditions to an object dynamically from an Array

I have an object like this, that needs to be sent to an API -
var data = {
field : "category"
value : "order"
}
Now, this API also needs some conditions needed to be sent as nested objects. Something like this -
var data ={
field : "category"
value : "order"
AND : {
field : "circuit"
value : "ninth"
OR : {
field : "second"
value : "abc",
//more conditions here possible //
}
}
So, basically, a condition is nested inside a condition.
EDIT:: Note - Each condition added into the conditions array has to be nested into the previous condition
Now, I have an array of conditions -
conditionsArray = [
{filter: "AND", field: "circuit", value: "ninth"},
{filter: "OR", field: "second", value: "abc"}
]
How do I add conditions to data object from this conditionsArray in the most optimal way?
var data = {
field : "category"
value : "order"
}
Thank you for your time.
EDIT: sorry, I forgot to add what I have tried so far -
I have been trying to just form an object but this is by no means a good solution.
const check = () => {
console.log(conditionsArray);
const data: any = { ...fieldValue };
conditionsArray.forEach((condition: any) => {
const { filter, name, value } = condition;
const { AND, OR, NOT } = data;
if (AND || OR || NOT) {
if (AND) {
data["AND"][filter] = { name, value };
}
if (OR) {
data["OR"][filter] = { name, value };
}
if (NOT) {
data["NOT"][filter] = { name, value };
}
} else {
data[filter] = { name, value };
}
});
console.log(data,"log data");
};
You could reduce the array and return the nested object for the next iteration.
const
data = { field: "category", value: "order" },
conditionsArray = [{ filter: "AND", field: "circuit", value: "ninth" }, { filter: "OR", field: "second", value: "abc" }];
conditionsArray.reduce((o, { filter, ...rest }) => o[filter] = rest, data);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using recursion :
function addConditions(data, conditions) {
if (conditions.length == 0) { return data; }
var topMostCondition = conditions[0];
var objectToAdd = { field : topMostCondition.field, value : topMostCondition.value };
data[topMostCondition.filter] = addConditions(objectToAdd, conditions.splice(1));
return data;
}
If your conditionsArray items should be added in the order of appearance to data, you may go recursive way like that:
const conditionsArray=[{filter:"AND",field:"circuit",value:"ninth"},{filter:"OR",field:"second",value:"abc"}],
data={field:"category",value:"order"},
makeATree = (o, list, branch) => {
if(!list.length) return o
const [condition, ...restOfConditions] = list,
{filter, ...rest} = condition
return makeATree(
{
...o,
...(
!branch ?
{[filter]: rest} :
{[branch]: {...o[branch], [filter]: rest}}
)
},
restOfConditions,
filter
)
}
console.log(makeATree(data, conditionsArray))
.as-console-wrapper{min-height:100%;}

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);

push to mongodb array using dynamic key

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 });

Categories

Resources