how Grouping JSON objects in .dmc file? - javascript

I have this sample of JSON :
{
"sending": {
"field": [
{
"email": "Sample String",
"id": 1234,
"name": "Sample String"
}, {
"email": "Sample String",
"id": 1234,
"name": "Sample String"
},{
"email": "Sample String",
"id": 1111,
"name": "Sample String"
}
]
}
}
I want to converted JSON to be grouping by id like this:
{
"sending": {
"field": [
{
"1234": [
{
"name": "Sample String",
"email": "Sample String"
},{
"name": "Sample String",
"email": "Sample String"
}
]
},
{
"1111": [
{
"name": "Sample String",
"email": "Sample String"
}
]
}
]
}
}
I wrote this code in .dmc file but it does not work as I want :
map_S_root_S_root = function(){
var outputroot={};
var a = 0;
outputroot = {};
outputroot.sending = {};
outputroot.sending.field = [];
for(i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491 in inputroot.sending.field){
outputroot.sending.field[a] = {};
id = inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].id;
outputroot.sending.field[a].id = [];
var c =0;
for(i in outputroot.sending.field[c].id){
if (inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].id === outputroot.sending.field[c].id){
outputroot.sending.field[c].id[c] += inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].name;
}
c++
}
outputroot.sending.field[a].id[a] = {};
outputroot.sending.field[a].id[a].name = inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].name;
outputroot.sending.field[a].id[a].email = inputroot.sending.field[i_field_1d3104f4_e7ee_449b_9653_ccc4f8985491].email;
a++;
}
return outputroot;
};
I use WSO2 data mapper mediator and write the code in .dmc file (data mapper configuration file ) in integration studio , could anyone help? Thanks

You can reduce it.
var array={ "sending": { "field": [ { "email": "Sample String", "id": 1234, "name": "Sample String" }, { "email": "Sample String", "id": 1234, "name": "Sample String" },{ "email": "Sample String", "id": 1111, "name": "Sample String" } ] }};
array.sending.field = array.sending.field.reduce((acc,{id, ...rest})=>{
acc[id] =acc[id] || [];
acc[id].push(rest);
return acc;
},{});
console.log(array);

The answer is
result = {
"field": [{
"id": "11",
"name": "asma",
"email": "asma#hotmail"
}, {
"id": "11",
"name": "jone",
"email": "jone#hotmail"
}, {
"id": "1234",
"name": "jak",
"email": "jak#hotmail"
}]
}
results = result.field;
groups = {};
for (var i in results) {
var groupName = results[i].id;
if (!groups[results[i].id]) {
groups[groupName] = [];
}
groups[groupName].push({"name" :results[i].name,"email":results[i].email})
}
console.log(groups);

Related

get key:value pair inside sub-blocks

I have the below output from Postman or hitting end point(we can say).
{
"SearchResult": {
"total": 11,
"resources": [
{
"id": "12345",
"name": "GuestType",
"description": "Identity group ",
},
{
"id": "56789",
"name": "Admin",
"description": "",
},
]
}
}
I want to extract "id" and "name" from these values. I see the values are inside sub-blocks.
How to extract these key-value using java-script that need to be put in "Tests" tab in postman?
var obj={
"SearchResult": {
"total": 11,
"resources": [
{
"id": "12345",
"name": "GuestType",
"description": "Identity group ",
},
{
"id": "56789",
"name": "Admin",
"description": "",
},
]
}
}
obj.SearchResult.resources.forEach((o)=>console.log(o.id,o.name));
Below code will return array of objects with id and name only.... Happy coding :)
let data = {
"SearchResult":
{
"total": 11,
"resources": [
{ "id": "12345", "name": "GuestType", "description": "Identity group ", },
{ "id": "56789", "name": "Admin", "description": "", }
]
}
}
let ids = data.SearchResult.resources.map(obj => {
id: obj.id,
name: obj.name
});
Try
let ids = data.SearchResult.resources.map(obj => obj.id);
let names = data.SearchResult.resources.map(obj => obj.name);
let data={ "SearchResult": { "total": 11, "resources": [ { "id": "12345", "name": "GuestType", "description": "Identity group ", }, { "id": "56789", "name": "Admin", "description": "", }, ] } }
let ids = data.SearchResult.resources.map(obj => obj.id);
let names = data.SearchResult.resources.map(obj => obj.name);
console.log(ids);
console.log(names);

o["postmore"] is not iterable

I want to transform created_time from CST to ISOString(ex:2019-02-22T17:43:05.000Z), so i need to get created_time.
But I have the question. When I use for(let...of...){} , I get the error
"o.postmore is not iterable".
How to fixed the codes to get created_time and transform the time?
{
"data": [
{
"text1": "123",
"desc": "xyz",
"postmore": [
{
"name": "haha",
"created_time": "2018-08-22 18:30:01 CST+0800"
},
{
"name": "gogo",
"created_time": "2018-08-22 18:30:01 CST+0800"
}]
},
{
"text1": "123",
"desc": "hjk",
"postmore": [
{
"name": "haha",
"created_time": "2018-08-23 18:30:01 CST+0800"
},
{
"name": "gogo",
"created_time": "2018-08-23 18:30:01 CST+0800"
}]
}]
}
this.http.get(url).subscribe(res =>{
this.testapi = res["data"];
for (let o of this.testapi){
o["text1"] = parseInt(o["text1"]);
for(let os of o["postmore"]){
os["created_time"] = new Date().toISOString();
console.log(os["created_time"]);
}
};
)

Get directory path in Array of Objects from directory path as string

Been searching SO posts, nothing answers this for me yet.
I have an Array of folders like such :
[{
"name": "home",
"folders": [{
"name": "New Folder",
"folders": [{
"name": "53w5r",
"folders": [{
"name": "test",
"folders": []
}]
}]
}, {
"name": "public folder",
"folders": [{
"name": "cold",
"folders": []
}, {
"name": "hot",
"folders": []
}]
}, {
"name": "My Folder",
"folders": []
}]
}]
I need to find search this array using a path string such as the following :
"home,New Folder,53w5r,test"
I'm searching for that folder, so a findFolder method would take the string above and return the folder objects in the "test" folder .
Assuming that your comma-separated path will always be valid, you can use this simple method for traversing the data:
var str = "home,New Folder,53w5r,test";
var data = [{
"name": "home",
"folders": [{
"name": "New Folder",
"folders": [{
"name": "53w5r",
"folders": [{
"name": "test",
"folders": []
}]
}]
}, {
"name": "public folder",
"folders": [{
"name": "cold",
"folders": []
}, {
"name": "hot",
"folders": []
}]
}, {
"name": "My Folder",
"folders": []
}]
}];
var folderNames = str.split(",");
var result = folderNames.reduce((results, folderName, index) => {
var currFolder = results.find(folder => folder.name === folderName);
// if last folder, return entire folder, otherwise return currFolder.folders
return index === folderNames.length-1 ? currFolder : currFolder.folders;
}, data);
console.log(result);
Here is my implementation without reduce, it will return null if the directory wasn't found.
const dirSeperator = ",";
function findDir(path, dirs) {
var parts = path.split(dirSeperator);
if (parts && parts.length > 0) {
var n = parts[0];
for (var i = 0; i < dirs.length; i++) {
if (dirs[i].name === n) {
if (parts.length > 1)
return findDir(path.replace(n + dirSeperator, ''), dirs[i].folders)
else if (parts.length == 1)
return dirs[i]
}
}
return null;
} else {
return null;
}
}
var dirs = [{
"name": "Test",
"folders": [{
"name": "Test2",
"folders": [{
"name": "test 3",
"folders": []
},
{
"name": "test 3",
"folders": []
}
]
}]
},
{
"name": "Main",
"folders": [{
"name": "Test2",
"folders": [{
"name": "test 3",
"folders": []
},
{
"name": "test 3",
"folders": []
}
]
}]
}
];
const testcase = "Test,Test2,test 3";
console.log('Searching for', testcase, ' in ', dirs)
console.log(findDir(testcase, dirs))
Here's a 2 line solution:
You can use the .find method to search for a folder on a level:
(folder, name) => folder.folders.find(e => e.name == name);
Then I have written a recursive function that will look up the folders for each element of the provided path. It uses .reduce to keep track of the parent folder (acc). At the end of the loop it returns the last folder array (the one at the end of the path).
path.split(',').reduce((acc, curr) => find(acc, curr), {folders:folders});
Here's a quick demo:
const find = (folder, name) => folder.folders.find(e => e.name == name);
const getFolders = path => path.split(',').reduce((acc, curr) => find(acc, curr), {folders:folders});
console.log(
getFolders('home,New Folder,53w5r,test')
);
<script>
const folders = [{
"name": "home",
"folders": [{
"name": "New Folder",
"folders": [{
"name": "53w5r",
"folders": [{
"name": "test",
"folders": []
}]
}]
}, {
"name": "public folder",
"folders": [{
"name": "cold",
"folders": []
}, {
"name": "hot",
"folders": []
}]
}, {
"name": "My Folder",
"folders": []
}]
}]
</script>

Create new javascript object from 2 JSON objects grouped by id

I have below dynamic nested JSON object arrays and I wanted to get the desired output with JavaScript grouped by id from both.
First Array:
[
{
"id": "11",
"name": "emp1",
"location": [
{ "name": "abc", "id": "lc1" }
]
},
{
"id": "11",
"name": "emp2",
"location": [
{ "name": "abc", "id": "lc1" },
]
},
{
"id": "22",
"name": "emp3",
"location": [
{ "name": "xyz", "id": "lc2" }
]
}
]
Second array like below.
[
{
"name": "sub1",
"id": "11"
...
},
{
"name": "sub1.1",
"id": "11"
...
},
{
"name": "sub2",
"id": "22"
...
}
]
Desired Output:
[
{
"id": "11",
"first": [{"name": "emp1"},
{"name": "emp2"}],
"second": [{"name": "sub1"},{"name": "sub1.1"}],
"location": [{"name": "abc"}]
},
{
"id": "22",
"first": [{"name": "emp3"}],
"second": [{"name": "sub2"}],
"location": [{"name": "xyz"}]
}
]
How to get the desired output like above using javascript/angularjs?
I would do it using the amazing Array#reduce function.
Note that I have named your first array as a1, second as a2 and result as res.
a1.reduce(function(arr, obj) {
var existing = arr.filter(function(res) {
return res.id === obj.id
})[0]
if (existing) {
existing.first.push({
name: obj.name
})
} else {
var second = a2.filter(function(res) {
return res.id === obj.id
})
var secondObj = second.length ? second.map(function(sec) {
return {
name: sec.name
};
}) : []
arr.push({
id: obj.id,
first: [{
name: obj.name
}],
second: secondObj,
location: obj.location
})
}
return arr;
}, [])
Here's the working snippet. Take a look!
var a1 = [{
"id": "11",
"name": "emp1",
"location": [{
"name": "abc",
"id": "lc1"
}]
},
{
"id": "11",
"name": "emp2",
"location": [{
"name": "abc",
"id": "lc1"
}]
},
{
"id": "22",
"name": "emp3",
"location": [{
"name": "xyz",
"id": "lc2"
}]
}
]
var a2 = [{
"name": "sub1",
"id": "11"
}, {
"name": "sub1.1",
"id": "11"
},
{
"name": "sub2",
"id": "22"
}
]
var res = a1.reduce(function(arr, obj) {
var existing = arr.filter(function(res) {
return res.id === obj.id
})[0]
if (existing) {
existing.first.push({
name: obj.name
})
} else {
var second = a2.filter(function(res) {
return res.id === obj.id
})
var secondObj = second.length ? second.map(function(sec) {
return {
name: sec.name
};
}) : []
arr.push({
id: obj.id,
first: [{
name: obj.name
}],
second: secondObj,
location: obj.location
})
}
return arr;
}, [])
console.log(res)
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
var red1 = [{
"id": "11",
"name": "emp1",
"location": [{
"name": "abc",
"id": "lc1"
}]
},
{
"id": "11",
"name": "emp2",
"location": [{
"name": "abc",
"id": "lc1"
}]
},
{
"id": "22",
"name": "emp3",
"location": [{
"name": "xyz",
"id": "lc2"
}]
}
]
var b = [{
"name": "sub1",
"id": "11"
},
{
"name": "sub2",
"id": "22"
}
]
var identication = {}
var result = []
red1.forEach(function(val) {
if (val['id'] in identication) {
var t = {}
t['name'] = val['name']
result[identication[val['id']]]['first'].push(t)
} else {
var t = {}
t['name'] = val['name']
val['first'] = []
val['first'].push(t)
delete val['name']
var identity = result.push(val)
identication[val['id']] = identity - 1;
}
})
b.forEach(function(d) {
if (d['id'] in identication) {
var t = {
'name': d['name']
}
if (!('second' in result[identication[d['id']]])) {
result[identication[d['id']]]['second'] = []
}
result[identication[d['id']]]['second'].push(t)
} else {
var t = {}
for (key in d) {
if (key == 'name')
continue
t[key] = d[key]
}
t['second'] = [{
'name': d['name']
}]
var identity = result.push(t)
identication[d['id']] = identity - 1;
}
})
console.log(result)

Jquery : transform nested json object to another json object

In javascript/jquery how do i achieve following
old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
Using jquery iterate over the above and change to following
new_dataset = [
{
"dob":"xyz",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
},{
"dob":"er",
"name": <first and last name values>
"start_date":<value of month day year>,
"children": [ {
child_id :1,
child_id : 2
},
]
}]
If someone can give the code to transform the data it would help me to understand the iteration
You could do something like:
function transformDataset(oldDataset) {
var newDataset = [];
var newObj;
for (var i = 0; i < oldDataset.length; i++) {
newObj = transformObj(oldDataset[i]);
newDataset.push(newObj);
}
return newDataset;
}
function transformObj(obj) {
var children = obj.children;
obj.name = obj.name.first + ' ' + obj.name.last;
obj.start_date = obj.start_date.month + ' ' + obj.start_date.day + ' ' + obj.start_date.year;
obj.children = [];
for (var i = 0; i < children.length; i++) {
obj.children.push(children[i].child.id);
}
return obj;
}
var new_dataset = transformDataset(old_dataset);
Note that new_dataset will have an array of child id instead of an object with multiple child_id properties.
You also had a typo in old_dataset.start_date.month (was written moth)(or maybe that was intentional).
use map first to iterate the array data (old_dataset), replace element name & start_date with new value then return the array
const old_dataset = [
{
"dob": "xyz",
"name": {
"first": " abc",
"last": "lastname"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
},
{
"dob": "er",
"name": {
"first": " abc",
"last": "txt"
},
"start_date": {
"moth": "2",
"day": "5",
"year": 1
},
"children": [
{
"child": {
"id": "1",
"desc": "first child"
}
},
{
"child": {
"id": "2",
"desc": "second child"
}
}
]
}
]
let new_dataset = old_dataset.map((arr) => {
arr.name = `${arr.name.first} ${arr.name.last}`
arr.start_date = `${arr.start_date.moth} ${arr.start_date.day} ${arr.start_date.year}`
return arr
})
console.log(new_dataset)

Categories

Resources