I need to consolidate an array containing JSON objects that were retrieved from a CSV file.
CSV file:
sector,subsector,codigo
sector1,subsector1,001
sector1,subsector2,002
sector2,subsector1,003
sector3,subsector1,004
sector3,subsector3,005
This is my code:
const csvtojson = function(){
let pathToCsv = './dummy-sectores.csv'
csv({
colParser:{
"sector.subsector":{
flat: true,
cellParser: "subsector"
}
}
})
.fromFile(pathToCsv)
.then((json) => {
const n = {}
json.forEach((a)=>{
n.sector = a.sector
n.subsector = a.subsector
})
console.log(n)
})
.catch((e) => console.log(e))
}
What I get:
[ { codigo: '001',
sector: 'sector 1',
subsector: 'sector 1 subsector 1' },
{ codigo: '002',
sector: 'sector 1',
subsector: 'sector 1 subsector 2' },
{ codigo: '003',
sector: 'sector 2',
subsector: 'sector 2 subsector 1' },
{ codigo: '004',
sector: 'sector 3',
subsector: 'sector 3 subsector 1' },
{ codigo: '005',
sector: 'sector 3',
subsector: 'sector 3 subsector 2' } ]
What I'm trying to get:
{
"sector1":
[{"subsector": "subsector1", "codigo": 1},
{"subsector": "subsector2", "codigo": 2}],
"sector2":
[{"subsector": "subsector1", "codigo": 3}],
"sector3":
[{"subsector": "subsector1", "codigo": 4},
{"subsector": "subsector2", "codigo": 5}]
}
Whenever I try to use map or forEach function it just messes up everything.
Quite easy - suppose you use this Keyang / node-csvtojson
My raw JSON parsed from your CSV placed to string looks like:
[{ "sector": "sector1", "subsector": "subsector1", "codigo": "001" },
{ "sector": "sector1", "subsector": "subsector2", "codigo": "002" },
{ "sector": "sector2", "subsector": "subsector1", "codigo": "003" },
{ "sector": "sector3", "subsector": "subsector1", "codigo": "004" },
{ "sector": "sector3", "subsector": "subsector3", "codigo": "005" }]
Formatting is not exactly same, but looks almost like JSON you wanted(?)
{"sector1":
[{"subsector":"subsector1","codigo":1},
{"subsector":"subsector2","codigo":2}],
"sector2":
[{"subsector":"subsector1","codigo":3}],
"sector3":
[{"subsector":"subsector1","codigo":4},
{"subsector":"subsector3","codigo":5}]}
const csvtojson = function() {
let CSV = 'sector,subsector,codigo\nsector1,subsector1,001\nsector1,subsector2,002\nsector2,subsector1,003\nsector3,subsector1,004\nsector3,subsector3,005';
csv({
colParser: {
"sector.subsector": {
flat: true,
cellParser: "subsector"
}
}
})
.fromString(CSV)
.then((json) => {
const n = {}
json.forEach((a) => {
n[a.sector] = n[a.sector] || [];
n[a.sector].push(a);
delete a.sector;
a.codigo = parseInt(a.codigo);
})
console.log(JSON.stringify(
n
).replace(/:\[/g, ':\n[').replace(/([^"]),([\{"])/g, '$1,\n$2'))
})
.catch((e) => console.log(e))
}
csvtojson();
<script src="https://cdn.rawgit.com/Keyang/node-csvtojson/d41f44aa/browser/csvtojson.min.js"></script>
Related
I have a javascript object as follows :
let hogwartsHeirarchy = {
Headmaster: [
{
name: "Professor Dumbledore",
key: 1,
Headmistress: [
{
name: "Minerva McGonagall",
key: 2,
StandByProfessor: [
{
name: "Rubeus Hagrid",
subject: "Potions Master",
key: 3,
Professor: [
{ name: "Horace Slughorn", key: 4 },
{ name: "Severus Snape", key: 4 },
],
},
{
name: "Alastor Moody",
subject: "Defense Against the Dark Arts",
key: 3,
Professor: [
{ name: "Remus Lupin", key: 4 },
{ name: "Gilderoy Lockhart", key: 4 },
],
},
],
},
],
},
],
};
I want to print/get each of the node value [headmaster, headmastress,..] and their corresponding child values. I tried various methods like looping through the array using a for loop, recurse etc, but unfortunately I am not able to get any value out of the nodes. Please help.
e.g : I used this :
printArray(hogwartsHeirarchy);
function printArray(arr){
for(var i = 0; i < arr.length; i++){
if(arr[i] instanceof Array){
console.log("true: ");
console.log("intermediate one : ",arr[i]);
printArray(arr[i]);
}else{
console.log("final one : ",arr[i]);
}
}
}
The values can be shown in this format:
Headmaster - name : Professor Dumbledore, key : 1
.
.
StandByProfessor - name : Robeus Hagrid, subject : Potion Master, key : 3
StandByProfessor - name : Alastor Moody, subject : Defence against the dark arts, key : 3
.
.
Professor - ...
Professor - ...
Professor - ...
Professor - ...
I would suggest restructuring so that the subordinates are always accessed with the same key, and thus can be visited very simply. I also made it so every node is a person, there's no object at the top that isn't a person. I left the variable name, but it now refers to Dumbledore directly.
let hogwartsHeirarchy =
{
name: "Professor Dumbledore",
role: "Headmaster",
key: 1,
subordinates: [
{
name: "Minerva McGonagall",
role: "Headmistress",
key: 2,
subordinates: [
{
name: "Rubeus Hagrid",
role: "StandByProfessor",
subject: "Potions Master",
key: 3,
subordinates: [
{ name: "Horace Slughorn", key: 4, role: "Professor" },
{ name: "Severus Snape", key: 4, role: "Professor" },
],
},
{
name: "Alastor Moody",
role: "StandByProfessor",
subject: "Defense Against the Dark Arts",
key: 3,
subordinates: [
{ name: "Remus Lupin", key: 4, role: "Professor" },
{ name: "Gilderoy Lockhart", key: 4, role: "Professor" },
],
},
],
},
],
};
function visitStaff(staffMember) {
if (staffMember.subordinates) {
for (const subordinate of staffMember.subordinates) {
visitStaff(subordinate);
}
}
console.log("Staff member:", staffMember);
}
visitStaff(hogwartsHeirarchy);
When setting up a data structure, it's important to think about how it will be accessed, and what are its defining parts. In this case, there are people, which are the nodes, and (subordinate) relationships, which are the edges of the graph.
In your original code, you had an object { Headmaster: [...] } — what does it represent? is it a person? no; is it a relationship? kind of, but no. It defines something about Dumbledoor, that he's the Headmaster, but not who or what he's the Headmaster of. So it's really just describing the role/job title of Dumbledoor, so it makes more sense as a property of the person. It's redundant as an object.
It helps to align your objects so they all represent something. You should be able to describe what each object and array is.
Given the data structure:
a) I assume that there will be only one array in each type of "title", and
b) that array will contain a list of objects of a similar structure as it's parent
It's possible ...
to use for..of in order to
iterate through each key on an object, and add them to a string. Because there are arrays that contains objects,
I can loop through them, and
do a recursive loop, by having the method calling itself.
const hogwartsHierarchy = { Headmaster: [{ name: "Professor Dumbledore", key: 1, Headmistress: [{ name: "Minerva McGonagall", key: 2, StandByProfessor: [{ name: "Rubeus Hagrid", subject: "Potions Master", key: 3, Professor: [{ name: "Horace Slughorn", key: 4 }, { name: "Severus Snape", key: 4 }] }, { name: "Alastor Moody", subject: "Defense Against the Dark Arts", key: 3, Professor: [{ name: "Remus Lupin", key: 4 }, { name: "Gilderoy Lockhart", key: 4 }] }] }] }] };
function printAllWithChilds(obj, prevProp) {
let listItem = (prevProp) ? ' -- ' + prevProp : '';
for (const property in obj) { // 1
if (obj[property] instanceof Array) {
obj[property].forEach((child_obj) => { // 3
listItem += printAllWithChilds(child_obj, property); // 4
});
} else {
listItem += `, ${property}: ${obj[property]}`; // 2
}
}
return listItem;
}
let listStr = printAllWithChilds(hogwartsHierarchy);
console.log(listStr);
I would honestly split up hogwartsHierarchy into smaller bits, following a kind of database structure, where primary_key is unique for each individual. These arrays doesn't make much sense, until you look at the variable professors and how their respectively belongs_to key corresponds to the standbyprofessors, where you can see that "Horace Slughorn" belongs to "Rubeus Hagrid".
const headermaster = {
name: "Professor Dumbledore",
primary_key: 1
};
const headmistress = {
name: "Minerva McGonagall",
primary_key: 2,
belongs_to: 1
};
const standbyprofessors = [{
name: "Rubeus Hagrid",
subject: "Potions Master",
primary_key: 3,
belongs_to: 2
},
{
name: "Alastor Moody",
subject: "Defense Against the Dark Arts",
primary_key: 4,
belongs_to: 2
}
];
const professors = [{
name: "Horace Slughorn",
primary_key: 5,
belongs_to: 3
},
{
name: "Severus Snape",
primary_key: 6,
belongs_to: 3
},
{
name: "Remus Lupin",
primary_key: 7,
belongs_to: 4
},
{
name: "Gilderoy Lockhart",
primary_key: 8,
belongs_to: 4
},
];
You could remove known keys from the object and get the type hierarchy then iterate the property and return the tupel of type, name, subject and key only if type exists.
const
getValues = (object, type) => [
...(type ? [`${type} - name : ${object.name}, ${object.subject ? `subject : ${object.subject}, ` : ''}key : ${object.key}`] : []),
...Object
.keys(object)
.filter(k => !['name', 'subject', 'key'].includes(k))
.flatMap(k => object[k].flatMap(o => getValues(o, k)))
],
hogwartsHierarchy = { Headmaster: [{ name: "Professor Dumbledore", key: 1, Headmistress: [{ name: "Minerva McGonagall", key: 2, StandByProfessor: [{ name: "Rubeus Hagrid", subject: "Potions Master", key: 3, Professor: [{ name: "Horace Slughorn", key: 4 }, { name: "Severus Snape", key: 4 }] }, { name: "Alastor Moody", subject: "Defense Against the Dark Arts", key: 3, Professor: [{ name: "Remus Lupin", key: 4 }, { name: "Gilderoy Lockhart", key: 4 }] }] }] }] };
console.log(getValues(hogwartsHierarchy));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Based on a 1j01 object model:
const hogwartsHeirarchy =
{ name: "Professor Dumbledore", role: "Headmaster", key: 1,
subordinates: [{ name: "Minerva McGonagall", role: "Headmistress", key: 2,
subordinates: [
{ name: "Rubeus Hagrid", role: "StandByProfessor", subject: "Potions Master", key: 3,
subordinates: [
{ name: "Horace Slughorn", key: 4, role: "Professor" },
{ name: "Severus Snape", key: 4, role: "Professor" }]},
{ name: "Alastor Moody", role: "StandByProfessor", subject: "Defense Against the Dark Arts", key: 3,
subordinates: [
{ name: "Remus Lupin", key: 4, role: "Professor" },
{ name: "Gilderoy Lockhart", key: 4, role: "Professor" }]}]}]};
const visitStaff = (staffMember) => {
const iter = (obj) => {
const { name, role, key, subordinates } = obj;
const subject = obj.subject ? `, subject : ${obj.subject}` : '';
const line = `${role} - name : ${name}${subject}, key : ${key}`;
const sublines = (Array.isArray(subordinates)) ? subordinates.flatMap(iter) : [];
return [line, ...sublines];
}
return iter(staffMember).join('\n');
}
console.log(visitStaff(hogwartsHeirarchy));
.as-console-wrapper { max-height: 100% !important; top: 0; }
This question already has answers here:
Merge two array of objects based on a key
(23 answers)
Closed 1 year ago.
I have a small exercise, to merge three arrays into one array by matching ID's, I'd like to add the likes and comments array into the posts array how would I go about this?
const posts =
[ { _id: 1
, message: 'this is post one'
, likes: [ { id: 1111 } , { id: 2222 } ]
, comments: [ { id: 3333 } , { id: 4444 } ]
}
]
const comments =
[ { id: 3333, message: 'this is comment 1' }
, { id: 4444, message: 'this is comment 2' }
]
const likes =
[ { id: 1111, user: 'Peter' }
, { id: 2222, user: 'John' }
]
expected output:
newArray =
[ { _id: 1
, message: 'this is post one'
, likes:
[ { id: 1111, user: 'Peter'}
, { id: 2222, user: 'John'} ]
, comments:
[ { id: 3333, message: 'this is comment 1'}
, { id: 4444, message: 'this is comment 2'}
] } ]
Here is a similar approach I've used when working with two arrays:
const
arr1 = [{ groupId: "Category", options: [{ name: "cookies", id: 1111 }, { name: "tv", id: 2222 }] }, { groupId: "Brand", options: [{ name: "random", id: 3333 }] }, { groupId: "Price", options: [{ name: "random2", id: 4444 }] }],
arr2 = [{ id: 1111, url: "/test", other: 'other-prop' }, { id: 2222, url: "/test1" }, { id: 3333, url: "/test2" }],
mergeById = (arr1, arr2) =>
arr1.map(({ options, ...rest }) => (
{
...rest,
options: options.map(option => (
{
...option,
...arr2.find(_option => _option.id === option.id)
}
))
}
));
const merged = mergeById(arr1, arr2);
console.log(JSON.stringify(merged, null, 2));
const newPosts = posts.map(post => ({
...post,
likes: likes.filter(like => post.likes.map(like => like.id).includes(like.id)),
comments: comments.filter(comment => post.comments.map(comment => comment.id).includes(comment.id)),
}))
console.log(newPosts)
How to change object to array of objects in javascript.
How to modify object and get the new aray of objects in javascript
Expected Result should be as input object weeks x 2 times (4 objects in output array)
for each item.
In Expected Output,
group key represents the weeks columns array,
should create a arraylist of each item desc, and interval qty per week
function createObject(obj){
const results = [];
for (var itm of obj.items) {
group: Object.values(obj.options).map((opt, index)=>opt.start+"-"+opt.end)
}
}
var obj = {
options: {
w1: {start:"Jan",end: "1"},
w2: {start:"Feb", end: "1"}
},
intervals: {
t1: {begin: "1", end: "2", totalqty: 2,totalamt: 200},
t2: {begin: "4", end: "7", totalqty: 3, totalamt: 300},
}
items: [
{
name: "s1",
desc: "sample1",
w1: {t1: {qty:0},t2: {qty:1}},
w2: {t1: {qty:1},t2: {qty:2}}
}
{
name: "s2",
desc: "sample2",
w1: {t1: {qty:0},t2: {qty:0}},
w2: {t1: {qty:0},t2: {qty:1}}
}
]
}
Expected Output:
[
{
group:"Jan 1", // represents w1
columns: [
{
col: 'desc',
value: 'sample1' // item.desc
},
{
col: '1-2', // represents t1
value: 0 , // represents t1.qty
},
{
col: '4-7', // represents t2
value: 1 // represents w1.t2.qty
}
]
},
{
group:"Feb 1", // represents w2
columns: [
{
col: 'desc',
value:'sample1'
},
{
col: '1-2', // represents t1
value:1 , // represents t1.qty
},
{
col: '4-7', // represents t2
value:2 ,// represents t2.qty
}
]
},
{
group:"Jan 1",
columns: [
{
col: 'desc',
value:'sample2'
},
{
col: '1-2',
value:0,
},
{
col: '4-7',
value:0
}
]
},
{
group:"Feb 1",
columns: [
{
col: 'desc',
value:'sample2'
},
{
col: '1-2',
value:0 ,
},
{
col: '4-7',
value:1,
}
]
}
]
Please try the below code. It produces the expected result
function createObject(obj){
return obj.items.map((item) => {
return Object.keys(obj.options).map((optKey) => {
const option = obj.options[optKey];
const items = {
'group' : `${option.start} ${option.end}`,
'columns': [{col: 'desc', value: item.desc}]
};
const intervals = item[optKey];
Object.keys(intervals).forEach((interval) => {
items.columns.push({
col: `${obj.intervals[interval].begin}-${obj.intervals[interval].end}`,
value: intervals[interval].qty
})
})
return items;
})
});
}
I have two objects. obj2 has texts and obj1 has 3 subIbjId. How can I add the 'id' to obj2 based on obj1?
For example: obj1 has 2 subObjId in the first object(1001, 1002). I want to count the number of subObjId obj1 has and iterate through obj1 and add the key and value of id for the to obj2. If obj1 has two subObjId, then add id: 1 to the first two entries of obj2 and so on.
I am learning javascript and trying to solve some imaginary problems. Any help would be greatly appreciated. Thank you.
var obj1 = { [
{
id: 1,
name: ‘apple’,
subObjId: [ 1001, 1002]
subObjs: [
{
subId: 1001
subName: ‘ant’,
},
{
subId: 1002
subName: ‘ball’,
}
],
},
{
{
id: 2,
name: ‘zebra’,
subObjId: [ 1003]
subObjs: [
{
subId: 1003
subName: ‘cat’,
}
],
},
]
}
var obj2 = { [
{
text: ‘i am a text’
},
{
text: ‘i am some random characters’
},
{
text: ‘i am some numbers’
}
] }
to become
finalObject = { [
{
id: 1,
text: ‘i am a text’
},
{
id: 1,
text: ‘i am some random characters’
},
{
id: 2,
text: ‘i am some numbers’
}
] }
Try this!!
var obj1 = [
{
id: 1,
name: 'apple',
subObjId: [ 1001, 1002]
},
{
id: 2,
name: 'zebra',
subObjId: [ 1003]
}
]
var obj2 = [
{
text: 'i am a text'
},
{
text: 'i am some random characters'
},
{
text: ' am some numbers'
}
]
let index = 0;
let start = 0;
obj1.map(data1=>{
index += data1.subObjId.length;
for(var i=start;i<index;i++){
obj2[i]['id'] = data1.id;
}
start = i;
})
console.log(obj2)
You can use
Array#flatMap to extract an array of all subObjs items
also Array#map them into their parent's id property only.
Perform another mapping operation that copies the contents of a matching object in obj2 and adds an id.
For convenience, this uses the second argument to Array#map, which sets the this context inside the callback.
Also uses destructuring for compactness and spread syntax for making copies:
var obj1 = [ { id: 1, name: 'apple', subObjId: [1001, 1002], subObjs: [ { subId: 1001, subName: 'ant' }, { subId: 1002, subName: 'ball' } ] }, { id: 2, name: 'zebra', subObjId: [1003], subObjs: [ { subId: 1003, subName: 'cat', } ], }, ];
var obj2 = [ { text: 'i am a text' }, { text: 'i am some random characters' }, { text: 'i am some numbers' } ];
var finalObject = obj1
//1. flatMap into a single array
.flatMap(({id, subObjs}) => subObjs
.map(sub => ({id})) //take only the parent ID for each sub object
)// result: [{id: 1}, {id: 1}, {id: 2}]
.map(function({id}, index) {
return { id, ...this[index] } //2. create a new object with the id and the content of a matching object from the other array
}, obj2);// <- set the `this` context for the callback
console.log(finalObject);
It can also be done as a single operation when flatmapping by setting the this context to a copy of the second array (to avoid mutating obj2), then taking items off the front of the new array with Array#shift:
var obj1 = [ { id: 1, name: 'apple', subObjId: [1001, 1002], subObjs: [ { subId: 1001, subName: 'ant' }, { subId: 1002, subName: 'ball' } ] }, { id: 2, name: 'zebra', subObjId: [1003], subObjs: [ { subId: 1003, subName: 'cat', } ], }, ];
var obj2 = [ { text: 'i am a text' }, { text: 'i am some random characters' }, { text: 'i am some numbers' } ];
var finalObject = obj1.flatMap(function({id, subObjs}) {
return subObjs.map(sub => ({ id, ...this.shift() }))
}, [...obj2]);// <- copy obj2 as the `this` context
console.log(finalObject);
Use this snippet
var obj1 = [
{
id: 1,
name: 'apple',
subObjId: [1001, 1002],
subObjs: [{
subId: 1001,
subName: 'ant',
},
{
subId: 1002,
subName: 'ball',
}
],
},
{
id: 2,
name: 'zebra',
subObjId: [1003],
subObjs: [{
subId: 1003,
subName: 'cat',
}],
},
]
var obj2 = [
{
text: 'i am a text'
},
{
text: 'i am some random characters'
},
{
text: 'i am some numbers'
}
]
var finalObject = obj1.map(function (value, index) {
return {
id: value.id,
text: obj2[index].text
}
})
console.log(finalObject)
I have multiple arrays and I want to merge the data of all the array into one array of objects .
All the data will be merged on the basis of the key so how to make one production level code so that it will merge all the data.
results[0]=
[ {categoryGroupID: '1231',categoryID: '12311',categoryName: 'External'},
{categoryGroupID: '1231',categoryID: '12312',categoryName: 'Internal'},
{categoryGroupID: '1231',categoryID: '141414141',categoryName: ''},
{categoryGroupID: '1232',categoryID: '12321',categoryName: 'Style'},
{categoryGroupID: '1233',categoryID: '123222',categoryName: ''},
{categoryGroupID: '1233',categoryID: '12331',categoryName: 'Customer Satisfaction'}]
results[1]=
[ { categoryGroupID: '1231',categoryGroupName: 'Store ambience'},
{ categoryGroupID: '1232',categoryGroupName: 'Communication'},
{categoryGroupID: '1233',categoryGroupName: 'Overall Satisfaction'},
{categoryGroupID: '12331',categoryGroupName: null}]
results[2]=
[ {categoryID: '12311',questionID: '12311111',questionName: 'tell me snything'},
{categoryID: '12312',questionID: '12311113',questionName: 'whatever'},
{categoryID: '12311',questionID: '123ques',questionName: 'ashjsh'},
{categoryID: '12311',questionID: '123test',questionName: null}]
results[3]=
[ { questionID: '12311113',choiceID: '1231111111',choiceValue: 'good'},
{ questionID: '12311113',choiceID: '1231111112',choiceValue: 'very good'},
{questionID: '12311113',choiceID: '12311113113',choiceValue: 'bad'}]
MY output should like this so how to do it
"categoryGroup":
[
{"categoryGroupID": "1231","categoryGroupName": "Store ambience",
"category": [
{"categoryID": "12312","categoryName": "Internal",
"question": [
{"questionID": "12311113","questionName": "whatever",
"choice": [
{"choiceID": "1231111111","choiceValue": "good"},
{"choiceID": "1231111112","choiceValue": "very good"},
{"choiceID": "12311113113","choiceValue": "bad",}
],
}]
},
{"categoryID": "12311","categoryName": "External",
"question": [
{"questionID": "12311111","questionName": "tell me snything",},
{"questionID": "123ques","questionName": "ashjsh",},
{"questionID": "123test","questionName": null,}
]},
{"categoryID": "141414141","categoryName": "",}]
},
{"categoryGroupID": "1232","categoryGroupName": "Communication",
"category": [
{"categoryID": "12321","categoryName": "Style"}]
},
{"categoryGroupID": "1233","categoryGroupName": "Overall Satisfaction",
"category": [
{"categoryID": "123222","categoryName": "",},
{"categoryID": "12331","categoryName": "Customer Satisfaction",}]
},
{"categoryGroupID": "12331","categoryGroupName": null}
]
Without going into the depths of all this and how you will pretty much need to manually handle all cases here is an example of how it can work (probably not should work).
This is based on the indexes (0, 1, 2, 3) of results will always be the same and employs the filter and map Array functions. For performance I am not sure how well this will work in a large scenario.
var results = {};
results[0] =
[{ categoryGroupID: '1231', categoryID: '12311', categoryName: 'External' },
{ categoryGroupID: '1231', categoryID: '12312', categoryName: 'Internal' },
{ categoryGroupID: '1231', categoryID: '141414141', categoryName: '' },
{ categoryGroupID: '1232', categoryID: '12321', categoryName: 'Style' },
{ categoryGroupID: '1233', categoryID: '123222', categoryName: '' },
{ categoryGroupID: '1233', categoryID: '12331', categoryName: 'Customer Satisfaction' }];
results[1] =
[{ categoryGroupID: '1231', categoryGroupName: 'Store ambience' },
{ categoryGroupID: '1232', categoryGroupName: 'Communication' },
{ categoryGroupID: '1233', categoryGroupName: 'Overall Satisfaction' },
{ categoryGroupID: '12331', categoryGroupName: null }];
results[2] =
[{ categoryID: '12311', questionID: '12311111', questionName: 'tell me snything' },
{ categoryID: '12312', questionID: '12311113', questionName: 'whatever' },
{ categoryID: '12311', questionID: '123ques', questionName: 'ashjsh' },
{ categoryID: '12311', questionID: '123test', questionName: null }];
results[3] =
[{ questionID: '12311113', choiceID: '1231111111', choiceValue: 'good' },
{ questionID: '12311113', choiceID: '1231111112', choiceValue: 'very good' },
{ questionID: '12311113', choiceID: '12311113113', choiceValue: 'bad' }];
var o = {
categoryGroup: results[1].map(function (categoryGroup) {
var categoryGroup = {
categoryGroupID: categoryGroup.categoryGroupID,
categoryGroupName: categoryGroup.categoryGroupName
};
categoryGroup['category'] = results[0].filter(function (item) { return item.categoryGroupID == categoryGroup.categoryGroupID })
.map(function (item) {
return {
categoryId: item.categoryID,
categoryName: item.categoryName,
question: results[2].filter(function (ques) { return ques.categoryID == item.categoryID })
.map(function (ques) {
return {
questionId: ques.questionID,
questionName: ques.questionName,
choice: results[3].filter(function (ch) { return ch.questionID == ques.questionID })
.map(function (ch) {
return {
choiceID: ch.choiceID,
choiceValue: ch.choiceValue
}
})
}
})
};
});
return categoryGroup;
})
};
console.log(o);
See this -> How to merge two arrays in Javascript and de-duplicate items
var array1 = ["1","2"];
var array2 = ["3", "4"];
var array3 = array1.concat(array2); // Merges both arrays
// [ '1', '2', '3', '4' ]
for the Apache Commons Lang Array Utils see this -> How can I concatenate two arrays in Java?
js versions are dojo http://dojotoolkit.org/reference-guide/1.10/dojo/_base/array.html and util-array https://www.npmjs.com/package/util-array
This is another dojo example http://dojo-toolkit.33424.n3.nabble.com/How-to-concatenate-arrays-in-Dojo-td3744293.html
http://wiki.servicenow.com/index.php?title=ArrayUtil