I have an array of objects (pre_finalTab_new below) like this:
My goal is to group them by "schema", and then by "tip" and insert into new array, something like this:
var celotnaTabela = {};
for (var nov in pre_finalTab_new)
{
var shema = pre_finalTab_new[nov].schema.trim();
var objekt_tip = pre_finalTab_new[nov].type.trim();
var objekt_name = pre_finalTab_new[nov].name.trim();
var tip = pre_finalTab_new[nov].tip.trim();
if (celotnaTabela[shema] === undefined)
{
celotnaTabela[shema] = [];
if (celotnaTabela[shema][tip] === undefined)
{
celotnaTabela[shema][tip] = [];
if (celotnaTabela[shema][tip][objekt_tip] === undefined)
{
celotnaTabela[shema][tip][objekt_tip] = [];
celotnaTabela[shema][tip][objekt_tip] = [objekt_name];
} else
celotnaTabela[shema][tip][objekt_tip].push(objekt_name);
}
} else
{
if (celotnaTabela[shema][tip] === undefined)
{
celotnaTabela[shema][tip] = [];
}
if (celotnaTabela[shema][tip][objekt_tip] === undefined)
{
celotnaTabela[shema][tip][objekt_tip] = [];
celotnaTabela[shema][tip][objekt_tip] = [objekt_name];
} else
{
if (!celotnaTabela[shema][tip][objekt_tip].includes(objekt_name))
celotnaTabela[shema][tip][objekt_tip].push(objekt_name);
}
}
}
Then if i output celotnaTabela, i got this:
Expanded:
Even more:
But the problem is, when i try to use JSON.stringify(celotnaTabela), i got this:
{"HR":[],"ZOKI":[]}
But i need it to be in a right format, so i can pass this object into AJAX call..
Can anyone help me with this, what am i doing wrong?
i hope i understood everything right you asked for.
Next time provide the testdata and the wished result in textform pls.
var obj = [
{ schema: "HR", type: " PACKAGE", name: "PAKET1", tip: "new_objects" },
{ schema: "HR", type: " PACKAGE", name: "PAKET2", tip: "new_objects" },
{ schema: "HR", type: " PROCEDURE", name: "ADD_JOB_HISTORY", tip: "new_objects" },
{ schema: "ZOKI", type: " TABLE", name: "TABELA2", tip: "new_objects" },
{ schema: "ZOKI", type: " TABLE", name: "TABELA3", tip: "new_objects" },
];
var out = {};
for (var i = 0, v; v = obj[i]; i++) {
var a = v.schema.trim();
var b = v.type.trim();
var c = v.tip.trim();
var d = v.name.trim();
if (!out.hasOwnProperty(a)) {
out[a] = {};
}
if (!out[a].hasOwnProperty(b)) {
out[a][b] = {};
}
if (!out[a][b].hasOwnProperty(c)) {
out[a][b][c] = []
}
out[a][b][c].push(d);
}
console.log(JSON.stringify(out, null, 2));
Related
I have the following function:
populateClinicRoomSelect(object) {
var selectArray = [];
var options = [];
for(var key in object) {
if(object.hasOwnProperty(key)) {
options = {
value: object[key].id,
label: object[key].RoomName,
};
selectArray = selectArray.concat(options);
}
}
return selectArray;
}
The idea is that takes two defined fields from the object array and places it in a new array. It works fine. I also have a few more functions exactly the same to this except the 'id' field and 'RoomName' field are different field names. Is there any way to pass 'id' and 'RoomName' as function variables to define them in the function?
Sure, you can pass field names as arguments and use [arg] accessors as you already do with [key]:
function populateClinicRoomSelect(object, valueField, labelField) {
var selectArray = [];
var options = [];
for(var key in object) {
if(object.hasOwnProperty(key)) {
options = {
value: object[key][valueField],
label: object[key][labelField],
};
selectArray = selectArray.concat(options);
}
}
return selectArray;
}
const object = {
a: {
id: 1,
room: 'first room'
},
b: {
id: 2,
room: 'second room'
}
}
const result = populateClinicRoomSelect(object, 'id', 'room');
console.log(result)
You mean like this?
function populateClinicRoomSelect(object, value, label) {
value = value || "id"; // defaults value to id
label = label || "RoomName"; // defaults label to RoomName
var selectArray = [];
var options = [];
for(var key in object) {
if(object.hasOwnProperty(key)) {
options = {
value: object[key][value],
label: object[key][label],
};
selectArray = selectArray.concat(options);
}
}
return selectArray;
}
let obj = { 1: { id:1, RoomName: "Blue Lounge" }, 2: { id:2, RoomName: "Red Lounge" } }
console.log(populateClinicRoomSelect(obj, 'id', 'RoomName'));
i have a javascript object as follows
obj = {"account_id-0":null,"option_item_id-0":1,"value-0":"wer","account_id-1":null,"option_item_id-1":2,"value-1":"kkk","account_id-2":null,"option_item_id-2":3,"value-2":"qqqqq"
....
"account_id-n":null,"option_item_id-n":6,"value-n":"see"
}
From the above object, i need to create the following structure
{"0": {
account_id: null,
option_item_id: 1,
value: "wer"
},
"1": {
account_id: null,
option_item_id: 2,
value: "kkk"
},
"2": {
account_id: null,
option_item_id: 2,
value: "qqqqq"
},
.
.
.
"n": {
account_id: null,
option_item_id: 6,
value: "see"
}
}
Any idea on how to implement this?
You can iterate through the all the keys, and use Array#reduce to contruct the resultant object.
let obj = {
"account_id-0": null,
"option_item_id-0": 1,
"value-0": "wer",
"account_id-1": null,
"option_item_id-1": 2,
"value-1": "kkk",
"account_id-2": null,
"option_item_id-2": 3,
"value-2": "qqqqq",
"account_id-n": null,
"option_item_id-n": 6,
"value-0": "see"
};
let result = Object.keys(obj).reduce((res, item) => {
let [key, index] = item.split('-');
if (!res[index]) {
res[index] = {};
}
res[index][key] = obj[item];
return res;
}, {});
console.log(result);
var obj = {
"account_id-0": null,
"option_item_id-0": 1,
"value-0": "wer",
"account_id-1": null,
"option_item_id-1": 2,
"value-1": "kkk",
"account_id-2": null,
"option_item_id-2": 3,
"value-2": "qqqqq"
};
var props = [];
function getObj(ind) {
for (var p in props) {
if (ind === p) {
return props[p];
}
}
}
for (var prop in obj) {
var parts = prop.split('-');
var key = parts[0];
var indx = parts[1];
var tmp = getObj(indx);
if (tmp == undefined) {
var x = {};
x[indx] = {};
x[indx][key] = obj[prop];
props.push(x);
} else {
tmp[indx][key] = obj[prop];
}
}
console.log(props);
This should be the straight forward way of maniplulating the object array with simple split() function.
Try this:
var keys = Object.keys(obj), i = 0
var arr = [], o = {}
for(var k in keys) {
if(keys[k].match(/\d*$/m) == i) {
o[keys[k].replace(/-\d*$/m,'')] = obj[keys[k]]
} else {
i++
arr.push(o)
o = {}
}
}
Here I am using an array instead of an object with the keys "0", "1", " 2", ... "n". I think it's way more convenient.
I have an object that looks like this:
{house_id+street_id+school_id: {...}, house_id2+street_id2+school_id2: {...}, ...}
So, each key of the object is a combination of a house_id a street_id and a school_id separated by '+' sign.
I want to be able to filter the object given a street_id, so for example, for the given object:
{40+30+20: { name: "john" }, 41+31+20: { name: "eli" } } and the street_id being 30, the returning object would be:
{40+30+20: "john"}
How can I do that filtering?
You can do it in the following way
let obj = {'40+30+20': { name: "john" }, '41+31+20': { name: "eli" } }
let result = Object.keys(obj).filter(e => e.match(/^.*\+30\+.*$/) != null).reduce((a, b) => {
a[b] = obj[b];
return a;
}, {});
console.log(result);
You can do something like this:
var data = {
'40+30+20': {
name: "john"
},
'41+31+20': {
name: "eli"
}
};
var search = '30';
var r = Object.keys(data).filter(function(key) {
return key.split('+').some(function(p) {
return p === search;
});
}).map(function(key) {
var o = {};
o[key] = data[key];
return o;
});
console.log(r);
Try with the filter function and a regular expression:
var myObj = {'40+30+20': { name: "john" }, '41+31+20': { name: "eli" } };
function filterByStreet(obj, streetId) {
var filteredKeys = Object.keys(obj).filter((key) => {
var patt = new RegExp("[^+]+[+]" + streetId + "[+][0-9]+");
return patt.test(key);
});
var outObj = {};
for(filteredKey of filteredKeys) {
outObj[filteredKey] = obj[filteredKey];
}
return outObj;
}
var filteredObj = filterByStreet(myObj, 30);
console.log(filteredObj);
I want to sum total depending for each department without duplicates.
Yesterday user #yBrodsky helped me with that and suggested to use SQL but today I want to add a couple options and I can't do this in sql.
Main problem:
I have an array like:
var data = [{
dept:"test",
task_time:"83"
},{
dept:"test",
task_time:"41"
},{
dept:"other",
task_time:"10"
}];
And I want to sum task_time for every dept: for example test = 124 and other = 10.
There is a function which should calculate it but it works like test = 83. test = 41 and other = 10. And shows every dept instead one with sum.
There is function.
var totalPerDept = {};
angular.forEach(data, function(item) {
if(!totalPerDept[item.dept]) {
totalPerDept[item.dept] = 0;
}
totalPerDept[item.dept] += parseFloat(item.task_time);
});
Here's the above as a snippet:
var data = [{
dept:"test",
task_time:"83"
},{
dept:"test",
task_time:"41"
},{
dept:"other",
task_time:"10"
}];
var totalPerDept = {};
angular.forEach(data, function(item) {
if(!totalPerDept[item.dept]) {
totalPerDept[item.dept] = 0;
}
totalPerDept[item.dept] += parseFloat(item.task_time);
});
console.log(totalPerDept);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
I did some modifications to your code to obtain an array with the result you want:
function sumDeptData() {
var data = [{
dept:"test",
task_time:"83"
},{
dept:"test",
task_time:"41"
},{
dept:"other",
task_time:"10"
}];
var totalPerDept = [];
angular.forEach(data, function(item) {
var index = findWithAttr(totalPerDept, 'dept', item.dept);
if (index < 0) {
totalPerDept.push({
dept: item.dept,
total: parseFloat(item.task_time)
});
} else {
totalPerDept[index].total += parseFloat(item.task_time);
}
});
return totalPerDept;
}
function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}
sumDeptData() returns [{"dept":"test","total":124},{"dept":"other","total":10}]
Here is an example using Plain JavaScript.
var data = [{
dept: "test",
task_time: "83"
}, {
dept: "test",
task_time: "41"
}, {
dept: "other",
task_time: "10"
}],
minArr = [];
data.forEach(function(v) {
if (!this[v.dept]) {
this[v.dept] = {
dept: v.dept,
task_time: 0
};
minArr.push(this[v.dept]);
}
this[v.dept].task_time = parseInt(this[v.dept].task_time) + parseInt(v.task_time);
}, {});
console.log(minArr);
I'm extending the haruki template to support sub parameters.
My JSDoc comment is:
/**
* #constructor Foobar
* param {Object} firstLevel
* param {Object} [firstLevel.secondLevel]
* param {Object} [firstLevel.secondLevel.thirdLevel]
*/
By default, haruki will export a flat array of parameters like this:
[
{ name: 'firstLevel' },
{ name: '[firstLevel.secondLevel]' },
{ name: '[firstLevel.secondLevel.thirdLevel]' }
]
But I need to get an output like this:
[
{
name: 'firstLevel',
parameters: [
{
name: 'secondLevel',
parameters: [
{ name: 'thirdLevel' }
]
}
]
}
My idea was to create an Object and then convert it to Array, doing so I can easily access to the nested parameters.
But I can't find a solution to the recursiveness problem...
My attempt is the one below:
function subParam(paramsObj, names, paramObj) {
if (names.length === 1) {
paramsObj[names[0]] = paramObj;
} else {
paramsObj[names[0]].parameters[names[1]] = paramObj;
}
}
if (element.params) {
var params = {};
for (i = 0, len = element.params.length; i < len; i++) {
var names = element.params[i].name.replace(/\[|\]/g, '').split('.');
var obj = {
'name': element.params[i].name,
'type': element.params[i].type? element.params[i].type.names : [],
'description': element.params[i].description || '',
'default': hasOwnProp.call(element.params[i], 'defaultvalue') ? element.params[i].defaultvalue : '',
'optional': typeof element.params[i].optional === 'boolean'? element.params[i].optional : '',
'nullable': typeof element.params[i].nullable === 'boolean'? element.params[i].nullable : ''
};
subParam(params, names, obj);
}
// convert object to array somehow
}
Ideas?
In JavaScript, key-value pairs where key is unique are best suited for Object and not Array.
Create your tree in an Object, then re-structure it to your desired Array
function transform(data) {
var o = {}, i, str;
function addPath(path) {
var parts = path.split('.'),
e = o, i = 0;
for (; i < parts.length; ++i) {
e = e[parts[i]] = e[parts[i]] || {};
}
}
function transformPathObject(dir, obj) {
var key, arr = [];
for (key in obj) {
arr.push(transformPathObject(key, obj[key]));
}
obj = {'name': dir};
if (arr.length) obj.parameters = arr;
return obj;
}
for (i = 0; i < data.length; ++i) {
str = data[i].name;
str = str.replace(/^\[(.*)\]$|(.*)/, '$1$2');
addPath(str);
}
return transformPathObject('__root__', o).parameters;
}
Usage
var data = [
{ name: 'firstLevel' },
{ name: '[firstLevel.secondLevel]' },
{ name: '[firstLevel.secondLevel.thirdLevel]' }
];
transform(data);
/*
[
{
"name": "firstLevel",
"parameters": [
{
"name": "secondLevel",
"parameters": [
{
"name": "thirdLevel"
}
]
}
]
}
]
*/
Please note that you didn't show Optional data in your desired output