Give the title:
row.push({"ticker" : PX_Hist[j]['ticker']});
Calcluate data with different timeframe parameters
const timeframes = [5,10,90,120,250,500];
for (let t = 0; t <= timeframes.length - 1; t++){
row.push({"move" : ((PX_Hist[j]['px'][PX_Hist[j]['px'].length-1]["adjusted_close"] / PX_Hist[j]['px'][PX_Hist[j]['px'].length-timeframes[t]]["adjusted_close"] -1))});
}
I am creating the following output with this code.
[
[
{
"ticker": "JPM"
},
{ "move": 0.01405944118170499 },
{ "move": 0.0337445573294628 },
{ "move": 0.1692882281117576 },
{ "move": 0.07636499188035195 },
{ "move": 0.8151371865267423 },
{ "move": 0.4537049320855997 }
],
[
{
"ticker": "C"
},
{ "move": -0.01295986622073586 },
{ "move": 0.002689694224235595 },
{ "move": 0.05544868117343582 },
{ "move": -0.0457495911125243 },
{ "move": 0.7837535634777528 },
{ "move": 0.05665004788714745 }
],
[
{
"ticker": "C"
},
{ "move": -0.01295986622073586 },
{ "move": 0.002689694224235595 },
{ "move": 0.05544868117343582 },
{ "move": -0.0457495911125243 },
{ "move": 0.7837535634777528 },
{ "move": 0.05665004788714745 }
],
]
I need to transpose the above array to something that I can easily bind to a table like below:
[{"ticker": "JPM", "5": 0.01405944118170499,"10": 0.0337445573294628,"90":
0.1692882281117576,"120": 0.07636499188035195,"250": 0.8151371865267423,"500":
0.4537049320855997}]
Any words of advice about how to do this in an elegant way?
You can so something like this, using map and for loop. But honestly I find this unnecessary. You could just do this from the get go in your loop. instead of pushing to row, you could try:
row[0][timeframes[t]] = "that long thing you have there"
const arr = [
[{
"ticker": "JPM"
},
{
"move": 0.01405944118170499
},
{
"move": 0.0337445573294628
},
{
"move": 0.1692882281117576
},
{
"move": 0.07636499188035195
},
{
"move": 0.8151371865267423
},
{
"move": 0.4537049320855997
}
],
[{
"ticker": "C"
},
{
"move": -0.01295986622073586
},
{
"move": 0.002689694224235595
},
{
"move": 0.05544868117343582
},
{
"move": -0.0457495911125243
},
{
"move": 0.7837535634777528
},
{
"move": 0.05665004788714745
}
],
[{
"ticker": "C"
},
{
"move": -0.01295986622073586
},
{
"move": 0.002689694224235595
},
{
"move": 0.05544868117343582
},
{
"move": -0.0457495911125243
},
{
"move": 0.7837535634777528
},
{
"move": 0.05665004788714745
}
],
]
const flatObj = (arr) => {
const flatObject = {};
const keys = ["ticker", "5", "10", "90", "120", "250", "500"]
for (let i = 0; i < arr.length; i++) {
for (const property in arr[i]) {
flatObject[keys[i]] = arr[i][property];
}
};
return flatObject;
}
const result = arr.map(ar => flatObj(ar))
console.log(result)
Related
I have a payload structure to add datas into db, each object have name with child array, db should add each object with parent id. how to handle these array in loop adding data in database?
payload structure:
{
"name": "food",
"child_categories": [
{
"name": "non-frozen",
"child_categories": [
{
"name":"non-branded",
"child_categories": [
{
"name":"food-grains",
"child_categories": [
{
"name":"rice"
},
{
"name": "atta"
},
{
"name": "maida"
},
{
"name": "sooji"
},
{
"name":"ragi"
},
{
"name": "jower"
},
{
"name": "bajra"
}
]
},
{
"name":"salt&spices",
"child_categories": [
{
"name":"whole-spices"
},
{
"name":"grounded-spices"
}
]
},
{
"name":"dried-condiments",
"child_categories": [
{
"name":"salt"
},
{
"name":"powders"
},
{
"name":"sugar"
},
{
"name":"jaggery"
}
]
},
{
"name": "edible-oil&ghee"
},
{
"name": "lentils",
"child_categories":[
{
"name":"all-dals"
},
{
"name":"all-rajma"
},
{
"name":"chanas"
},
{
"name":"millets"
},
{
"name":"soya"
}
]
}
]
},
{
"name":"branded",
"child_categories": [
{
"name":"food-grains",
"child_categories": [
{
"name":"rice"
},
{
"name": "atta"
},
{
"name": "maida"
},
{
"name": "sooji"
},
{
"name":"ragi"
},
{
"name": "jower"
},
{
"name": "bajra"
}
]
},
{
"name":"salt&spices",
"child_categories": [
{
"name":"whole-spices"
},
{
"name":"grounded-spices"
}
]
},
{
"name":"dried-condiments",
"child_categories": [
{
"name":"salt"
},
{
"name":"powders"
},
{
"name":"sugar"
},
{
"name":"jaggery"
}
]
},
{
"name": "edible-oil&ghee"
},
{
"name": "lentils",
"child_categories":[
{
"name":"all-dals"
},
{
"name":"all-rajma"
},
{
"name":"chanas"
},
{
"name":"millets"
},
{
"name":"soya"
}
]
},
{
"name":"snacks&cereals",
"child_categories":[
{
"name":"biscuits"
},
{
"name":"cookies"
},
{
"name":"bhujia"
},
{
"name":"mixture"
}
]
},
{
"name":"packaged-raw",
"child_categories":[
{
"name":"noodles"
},
{
"name":"pasta"
},
{
"name":"macaroni"
},
{
"name":"spreads"
},
{
"name":"sauces"
},
{
"name":"ready-to-eat"
},
{
"name":"chocs"
},
{
"name":"pickles&chutney"
}
]
}
]
}
]
}
]
}
Each categories have sub categories,with up level parent_id, once first level category added, it should take that id, add it into child category. example structure below
{
_id: "1",
parent_category_id: null, // 1st level category
name:"food"
}
{
_id:2,
parent_category_id: 1,
name: "non-frozen"
}
{
_id: 3,
parent_category_id: 2,
name: "non-branded"
}
{
_id: 4,
parent_category_id: 3,
name: "food-grains"
}
and so on...
let payload = req.payload
let obj1 = {
"name": payload.name,
"parent_category_id": null,
"created_by": userId,
"updated_by": userId
}
let parent_category = await Category.create(obj1)
if (!!payload.childCategories){
payload.childCategories.forEach(async item => {
if(!!item){
let obj2 = {
"name": item.name,
"parent_category_id": parent_category._id,
"created_by": userId,
"updated_by": userId
}
let parent_category1 = await Category.create(obj2)
if (!!item.childCategories){
payload.childCategories.forEach(async item1 => {
let obj3 = {
"name": item1.name,
"parent_category_id": parent_category1._id,
"created_by": userId,
"updated_by": userId
}
let parent_category2 = await Category.create(obj3)
})
}
}
})
}
My quick thought was to solve the problem with the recursive function. It can be solved in other ways as well. But I like recursive functions. They are legible.
async function addCategory(payload, parent = null) {
const category = await Category.create({
name: payload.name,
parent_category_id: parent ? parent.id : null,
created_by: userId,
updated_by: userId
});
if(Array.isArray(payload.child_categories)) {
for(const child of payload.child_categories) {
addCategory(child, category);
}
}
}
I have a batch of JSON files
looking like this :
{
"properties": [
{
"Frame": "Yellow"
},
{
"Sky": "Apocalypse"
},
{
"Grass": "green"
},
{
"Sign": "sign"
},
{
"Graffitis": "shit"
},
{
"Things": "can"
},
{
"Quotes": "emptyness"
},
{
"Border": "framing"
},
{
"Logo": "logo"
},
{
"Overlay": "overlay"
}
]
}
And I want to modify them so they look like this :
{
Border: "framing",
Frame: "Yellow",
Graffitis: "shit",
Grass: "green",
Logo: "logo",
Overlay: "overlay",
Quotes: "emptyness",
Sign: "sign",
Sky: "Apocalypse",
Things: "can"
}
How can I achieve this?
Use Object.assign like so
const input = {
"properties": [
{
"Frame": "Yellow"
},
{
"Sky": "Apocalypse"
},
{
"Grass": "green"
},
{
"Sign": "sign"
},
{
"Graffitis": "shit"
},
{
"Things": "can"
},
{
"Quotes": "emptyness"
},
{
"Border": "framing"
},
{
"Logo": "logo"
},
{
"Overlay": "overlay"
}
]
}
const output = Object.assign({}, ...input.properties);
You can use Array.prototype.reduce() and spread syntax to accomplish this in one line:
let obj = {
"properties": [{
"Frame": "Yellow"
}, {
"Sky": "Apocalypse"
}, {
"Grass": "green"
}, {
"Sign": "sign"
}, {
"Graffitis": "shit"
}, {
"Things": "can"
}, {
"Quotes": "emptyness"
}, {
"Border": "framing"
}, {
"Logo": "logo"
}, {
"Overlay": "overlay"
}]
}
console.log(obj["properties"].reduce((prev, current) =>
({ ...prev,
...current
}), {}))
Hey and welcome to StackOverflow!
I recommend using a for-loop to iterate through an object you have parsed from the json (JS read json file and use as an object):
let newObject = {};
properties.forEach(property => {
Object.assign(newObject, property);
}
return newObject;
I have below data,
What i want to do is, i need to check values[] array in each object,
if it is empty then return true, else if values[] array has some record, it will return false.
i have created function for this, but it is reuturning false everytime.
if it is true thn i want to hide table. Table are multiple not single one, so if values arrayis empty thn only want to hide particular table.
{
"records": [
{
"context": {
"team": [
"MYTEAM-Consume-TEAM-SETUP-ADMIN"
]
},
"values": []
},
{
"context": {
"team": [
"TEAM1"
]
},
"values": [
{
"value": "red",
"label": "dd"
}
]
},
{
"context": {
"team": [
"Test"
]
},
"values": []
},
]
}
Code
hideContextTable(rows) {
const data = rows;
if (data.records) {
data.records.forEach(function (record) {
if (record.values.length === 0) {
return true;
}
});
}
return false;
}
deleteAllContextData(data) {
const tbl = this.hideContextTable(data);
console.log(tbl,"tbl");
if (tbl) {
this.showContextTables = false;
}
}
Simply check the length of returned data from filter function.
data = {
"records": [
{
"context": {
"team": [
"MYTEAM-Consume-TEAM-SETUP-ADMIN"
]
},
"values": []
},
{
"context": {
"team": [
"TEAM1"
]
},
"values": [
{
"value": "red",
"label": "dd"
}
]
},
{
"context": {
"team": [
"Test"
]
},
"values": []
},
]
};
function hideContextTable(data) {
const result = data.records.filter(record => record.values.length);
const flag = result.length ? true : false;
console.log(flag)
}
hideContextTable(data);
return in the higher order function of forEach will not cause flow to leave the hideContextTable function. You should use a variable that is accessible from outside that function and set it if the condition is met, then return that variable at the end of the function.
const rows = {
"records": [
{
"context": {
"team": [
"MYTEAM-Consume-TEAM-SETUP-ADMIN"
]
},
"values": []
},
{
"context": {
"team": [
"TEAM1"
]
},
"values": [
{
"value": "red",
"label": "dd"
}
]
},
{
"context": {
"team": [
"Test"
]
},
"values": []
},
]
}
function hideContextTable(rows) {
let isEmpty = false;
const data = rows;
if (data.records && data.records.values) {
data.records.forEach(function (record) {
if (record.values.length === 0) {
isEmpty = true;
return; // this is a higher order function
// meaning: it won't leave the context of hideContextTable
}
});
}
return isEmpty;
}
const test = hideContextTable(rows);
console.log(test);
I'm trying to loop through all the conditions for a form logic system utilizing the json-logic-js library and having issues going into the infinite nested conditions. It works when there is no additional nested operations but can't figure out away to loop through and detect if the condition contains additional conditions infinitely..
What I'm needing is this output
{
"or": [
{
"==": [
"0hxsj03jab9pjsu1",
"Rig 15"
]
},
{
"or": [
{
"==": [
"5l12cnsnxe1911bm",
"Corporate"
]
},
{
"==": [
"5l12cnsnxe1911bm",
"Pumping"
]
}
]
},
{
"and": [
{
"==": [
"69vsm5bkfb101n2n",
"Unsafe"
]
},
{
"or": [
{
"==": [
"b09ivo9r1aldu6jf",
"Yes"
]
},
{
"==": [
"0hxsj03jab9pjsu1",
"Rig 44"
]
},
{
"==": [
"0hxsj03jab9pjsu1",
"Other"
]
}
]
}
]
}
]
}
I currently have this much.
var item = {
"id":"8wj4xhwe3pd9aage",
"showif": {
"operator": "or",
"conditions": [
{
"operator": "and",
"conditions": [
{
"data": {
"fieldId": "69vsm5bkfb101n2n",
"settings": {
"values": [
"Unsafe"
]
}
}
},
{
"operator": "or",
"conditions": [
{
"data": {
"fieldId": "b09ivo9r1aldu6jf",
"settings": {
"values": [
"Yes"
]
}
}
},
{
"data": {
"fieldId": "0hxsj03jab9pjsu1",
"settings": {
"values": [
"Rig 44",
"Other"
]
}
}
}
]
}
]
},
{
"data": {
"fieldId": "0hxsj03jab9pjsu1",
"settings": {
"values": [
"Rig 15"
]
}
}
},
{
"data": {
"fieldId": "5l12cnsnxe1911bm",
"settings": {
"values": [
"Corporate",
"Pumping"
]
}
}
}
]
}
};
var condition = [];
item.showif.conditions.forEach(element => {
var orC = []
if(element.data){
element.data.settings.values.forEach(values => {
if(element.data.settings.values.length <= 1){
condition.push({"==": [element.data.fieldId,values]})
}else{
orC.push({"==": [element.data.fieldId,values]})
}
});
if(orC.length >= 1){
condition.push({"or":orC})
}
}
});
var Logic = {[item.showif.operator]: condition}
console.log(Logic)
I cant wrap my brain around this without getting lost..
I figured it out. For anyone else with this here is my code :)
var item = {
"id": "8wj4xhwe3pd9aage",
"showif": {
"operator": "or",
"conditions": [
{
"operator": "and",
"conditions": [
{
"data": {
"fieldId": "69vsm5bkfb101n2n",
"settings": {
"values": [
"Unsafe"
]
}
}
},
{
"operator": "or",
"conditions": [
{
"data": {
"fieldId": "b09ivo9r1aldu6jf",
"settings": {
"values": [
"Yes"
]
}
}
},
{
"data": {
"fieldId": "0hxsj03jab9pjsu1",
"settings": {
"values": [
"Rig 44",
"Other"
]
}
}
}
]
}
]
},
{
"data": {
"fieldId": "0hxsj03jab9pjsu1",
"settings": {
"values": [
"Rig 15"
]
}
}
},
{
"data": {
"fieldId": "5l12cnsnxe1911bm",
"settings": {
"values": [
"Corporate",
"Pumping"
]
}
}
}
]
}
};
function loopThrough(obj) {
var operator = obj.operator
var condition = [];
obj.conditions.forEach(element => {
var orC = []
if (element.data) {
element.data.settings.values.forEach(values => {
if (element.data.settings.values.length <= 1) {
condition.push({
"==": [element.data.fieldId, values]
})
} else {
orC.push({
"==": [element.data.fieldId, values]
})
}
});
if (orC.length >= 1) {
condition.push({
"or": orC
})
}
} else if (element.operator) {
condition.push(this.loopThrough(element))
}
});
return ({
[operator]: condition
})
}
console.log(loopThrough(item.showif));
Here is my sample Data:
{
"_id": {
"$oid": "5654a8f0d487dd1434571a6e"
},
"ValidationDate": {
"$date": "2015-11-24T13:06:19.363Z"
},
"DataRaw": " WL 00100100012015-08-28 02:44:17+0000+ 16.81 8.879 1084.00",
"ReadingsAreValid": true,
"locationID": " WL 001",
"Readings": {
"pH": {
"value": 8.879
},
"SensoreDate": {
"value": {
"$date": "2015-08-28T02:44:17.000Z"
}
},
"temperature": {
"value": 16.81
},
"Conductivity": {
"value": 1084
}
},
"HMAC":"ecb98d73fcb34ce2c5bbcc9c1265c8ca939f639d791a1de0f6275e2d0d71a801"
}
I am trying to group average values by two hours interval and have the following aggregation query.
Query = [{"$unwind":"$Readings"},
{'$group' : { "_id": {
"year": { "$year": "$Readings.SensoreDate.value" },
"dayOfYear": { "$dayOfYear": "$Readings.SensoreDate.value" },
"interval": {
"$subtract": [
{ "$hour": "$Readings.SensoreDate.value"},
{ "$mod": [{ "$hour": "$Readings.SensoreDate.value"},2]}
]
}
}},
'AverageTemp' : { '$avg' : '$Readings.temperature.value'}, "AveragePH": {"$avg" : "$Readings.pH.value"}, "AverageConduc": {"$avg" : "$Readings.Conductivity.value"}}
, {"$limit":10}]
This gives me an error saying
A pipeline stage specification object must contain exactly one field. and I have done all research but can't get the desired results.
After some formatting, your present aggregation pipeline looks like:
Query = [
{ "$unwind": "$Readings" },
{
'$group' : {
"_id": {
"year": { "$year": "$Readings.SensoreDate.value" },
"dayOfYear": { "$dayOfYear": "$Readings.SensoreDate.value" },
"interval": {
"$subtract": [
{ "$hour": "$Readings.SensoreDate.value"},
{
"$mod": [
{ "$hour": "$Readings.SensoreDate.value" },
2
]
}
]
}
}
},
'AverageTemp' : { '$avg' : '$Readings.temperature.value' },
"AveragePH": { "$avg" : "$Readings.pH.value" },
"AverageConduc": { "$avg" : "$Readings.Conductivity.value" }
},
{ "$limit": 10 }
]
with which mongo is complaining
A pipeline stage specification object must contain exactly one field.
because it's failing to recognise the misplaced fields
'AverageTemp' : { '$avg' : '$Readings.temperature.value' },
"AveragePH": { "$avg" : "$Readings.pH.value" },
"AverageConduc": { "$avg" : "$Readings.Conductivity.value" }
A correct pipeline should have these fields within the $group pipeline stage, so a working pipeline follows:
Query = [
{ "$unwind": "$Readings" },
{
"$group" : {
"_id": {
"year": { "$year": "$Readings.SensoreDate.value" },
"dayOfYear": { "$dayOfYear": "$Readings.SensoreDate.value" },
"interval": {
"$subtract": [
{ "$hour": "$Readings.SensoreDate.value"},
{
"$mod": [
{ "$hour": "$Readings.SensoreDate.value" },
2
]
}
]
}
},
"AverageTemp" : { "$avg" : "$Readings.temperature.value" },
"AveragePH": { "$avg" : "$Readings.pH.value" },
"AverageConduc": { "$avg" : "$Readings.Conductivity.value" }
}
},
{ "$limit": 10 }
]