Dynamic Mapping using jquery.map() - javascript

I have a series of ajax json responses that I need to convert to a common type of array. The issue is that each json response is slightly different.
Here are two examples of responses I might receive:
var contacts = [{ "ContactId" : "1", "ContactName" : "Bob" },{ "ContactId" : "2", "ContactName" : "Ted" }];
var sites = [{ "SiteId" : "1", "Location" : "MN" },{ "SiteId" : "2", "Location" : "FL" }];
I'm trying to write a method that converts either collection to a common type. An example of the above responses converted would look like this:
var convertedContacts = [{ "value" : "1", "text" : "Bob" },{ "value" : "2", "text" : "Ted" }];
var convertedSites = [{ "value" : "1", "text" : "MN" },{ "value" : "2", "text" : "FL" }];
So I'm trying to use the map function of jquery to facilitate this requirement. Although I can't seem to figure out how to dynamically query for the different property values that will exist depending on which json collection I'm passing into the function.
Here is an example of what I'm trying to do:
function ConvertResponse(arrayToConvert, text, value)
{
var a = $.map(arrayToConvert, function(m) {
return "{ \"text\" : "+eval("m."+text)+", \"value\" : "+eval("m."+value)+" }"
});
}
I also tried this:
function ConvertResponse(arrayToConvert, text, value)
{
var a = $.map(arrayToConvert, function(m) {
return "{ \"text\" : " + m.$(text) + ", \"value\" : " + m.$(value) + " }";
});
}
And this is how you would call it:
var convertedContacts = ConvertResponse(contacts, "ContactName", "ContactId");
var convertedSites = ConvertResponse(contacts, "Location", "SiteId");
Unfortunately this does not seem to work in the least.

Like this?
var contacts = [{ "ContactId" : "1", "ContactName" : "Bob" },{ "ContactId" : "2", "ContactName" : "Ted" }];
var sites = [{ "SiteId" : "1", "Location" : "MN" },{ "SiteId" : "2", "Location" : "FL" }];
function convertResponse(response, text, value) {
return $.map(response, function(it) {
return {
value: it[value],
text: it[text]
};
});
}
var convertedContacts = convertResponse(contacts, 'ContactId', 'ContactName');
var convertedSites = convertResponse(sites, 'SiteId', 'Location');

Related

Filter nested object structure

I have an object with keys representing a schema. A schema contains a definition of columns and I want to end up with a list of columns that match a specific condition. I can use a for each but think it should also be possible to achieve with a filter or reduce; however getting stuck accessing the nested portion and accumulate the results.
I tried a number of variants, with reduce, spread operators but not achieving the desired result.
Hope anyone can pull me out of the quicksand, I tend to sink deeper with every move I make.
<script type="text/javascript">
let data = {
"Schema A" : [{"Id" : "1", "Type" : "measure"}, {"Id" : "2", "Type" : "dimension"}, {"Id" : "3", "Type" : "measure"}],
"Schema B" : [{"Id" : "4", "Type" : "measure"}, {"Id" : "5", "Type" : "dimension"}, {"Id" : "6", "Type" : "measure"}],
};
var d = Object.entries(data); // convert to array
console.log(d);
let result = d.map(val => {
return val.filter(x => x[1].Type === 'measure');
});
console.log(result);
</script>
You need to take the values from the key/value entries for filtering.
const
data = { "Schema A": [{ Id: "1", Type: "measure" }, { Id: "2", Type: "dimension" }, { Id: "3", Type: "measure" }], "Schema B" : [{ Id: "4", Type: "measure" }, { Id: "5", Type: "dimension" }, { Id: "6", Type: "measure" }] },
result = Object
.entries(data)
.map(([k, v]) => [k, v.filter(({ Type }) => Type === 'measure')]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to compare two json object, check if id is same then assign to another object value?

I have two objects
var JSON_Categories = '[{ "id" : "1", "text" : "Category A"}, { "id" : 2, "text" : "Category B" }]';
var JSON_Article = '[{ "id" : "1", "text" : "Article text A"}, { "id" : 3, "text" : "Article B"}]';
var categories = JSON.parse(JSON_Categories);
var article = JSON.parse(JSON_Article);
if id match for both JSON value then, I need to assign text category text value with an article text value.
it tried something like this, I know it's not a good solution can anyone help me on it?
var categoryValue = new Object();
categories.forEach(function(category) {
articles.forEach(article => {
if (category.id === article.id) {
categoryValue.id = category.id;
categoryValue.text = article.text;
} else {
categoryValue.id = category.id;
categoryValue.text = category.text;
}
});
});
console.log('categoryValue', categoryValue);
You can map it and inside that find the Object from second array:
var JSON_Categories = JSON.parse('[{ "id" : "1", "text" : "Category A"}, { "id" : 2, "text" : "Category B" }]');
var JSON_Article = JSON.parse('[{ "id" : "1", "text" : "Article text A"}, { "id" : 3, "text" : "Article B"}]');
var result = JSON_Categories.map(({id, text})=>({id, text:JSON_Article.find(k=>k.id==id)?.text || text}));
console.log(result);

How to display all fields of a nested json in table format using Bootstrap

I want to write a utility which connects to a REST api downloads data in JSON format and then paints the data as nested tables using Bootstrap.
JSON Data -
[
{
"id" : "Id1",
"name" : "Name1",
"orders" : [{"orderId" : "o1", "size" : 34}, {"orderId" : "o2", "size" : 3}]
},
{
"id" : "Id2",
"name" : "Name2",
"orders" : [
{"orderId" : "o3", "size" : 5, "addresses" : [{"addressId" : "a1", "phone" : "1235"}, {"addressId" : "a2", "phone" : 555}]},
{"orderId" : "o4", "size" : 5, "addresses" : [{"addressId" : "a3", "phone" : "1235"}]}
]
}
]
I looked at the sub-table feature of Bootstrap, however it seems that it would need lot of custom code to get this working. Is there a better way to bind the json to table in a generic way?
Edit
After spending some time I was able to achieve this -
As you can see, I could get one level of nesting, however i just need to go one level deep. Any suggestions?
<script>
var $table = $('#table')
function buildTable($el, jsonData) {
var i; var j; var row
var columns = []
var data = []
if(!Array.isArray(jsonData) && jsonData.length == 0) {
return;
}
Object.keys(jsonData[0]).forEach( (k) => {
columns.push({
field: k,
title: k,
sortable: true
})
})
for(var j = 0; j < jsonData.length; j++) {
row = {}
Object.keys(jsonData[j]).forEach( (k) => {
row[k] = jsonData[j][k]
})
data.push(row)
}
$el.bootstrapTable({
columns: columns,
data: data,
detailFilter: function (index, row) {
console.log("detail filter " + Object.values(row))
for(var k in row) {
if(Array.isArray(row[k])){
return true;
}
}
return false;
},
onExpandRow: function (index, row, $detail) {
console.log("expand row keys " + Object.keys(row))
console.log("expand row vals " + Object.values(row))
var newRow = {};
for(var k in row) {
if(Array.isArray(row[k])){
alert('found ' + row[k])
newRow = row[k]
break
}
}
buildTable($detail.html('<table></table>').find('table'), newRow)
}
})
};
var mydata =
[
{
"id": 0,
"name": "test0",
"price": "$0",
"orders" :
[
{
"name" : "ABC",
"size" : 25,
"someList": [{"a":1, "b":2}, {"a":3, "b":4}]
},
{
"name" : "XYZ",
"size" : 50
}
]
}
/* {
"id": 1,
"name": "test1",
"price": "$1"
},
{
"id": 2,
"name": "test2",
"price": "$2",
"orders" : [{"name" : "def", "size": 45}]
}*/
];
$(function() {
buildTable($table, mydata)
})

object transformation with underscore.js

For whatever reason, I have quite a bit of difficulty when trying to transform objects and arrays.
The current data I have is stored in a mongodb collection and looks like this:
[{ "_id" : 1, "name" : "someName", "colorName" : "Pink"},
{ "_id" : 2, "name" : "someName2", "colorName" : "RoyalBlue"},
{ "_id" : 3, "name" : "aThirdOne", "colorName" : "Gold"},
{ "_id" : 4, "name" : "oneMore", "colorName" : "LightGreen"}]
I need to get either the following two arrays, but would like to know how to get both.
[{ "value" : 1, "label" : "someName"},
{ "value" : 2, "label" : "someName2"},
{ "value" : 3, "label" : "aThirdOne"},
{ "value" : 4, "label" : "oneMore"]
[{1 : "someName"},
{2 : "someName2"},
{3 : "aThirdOne"},
{4 : "oneMore"}]
I know it is probably something with _.map, but I am not sure why I can't figure it out. Please advise.
You don't really need Underscore for this, it's just normal Array.prototype.map method usage (although Underscore also provides this method):
var data = [{ "_id" : 1, "name" : "someName", "colorName" : "Pink"},
{ "_id" : 2, "name" : "someName2", "colorName" : "RoyalBlue"},
{ "_id" : 3, "name" : "aThirdOne", "colorName" : "Gold"},
{ "_id" : 4, "name" : "oneMore", "colorName" : "LightGreen"}];
var result = data.map(function(el, i) {
return {value: el._id, label: el.name};
});
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre>';
Also note, that your second data structure doesn't make sense because it's irregular, so don't use it, it's not very convenient at all.
And here is corresponding Underscore version:
// Or Underscore version
var result = _.map(data, function(el) {
return {value: el._id, label: el.name};
});
In plain Javascript you can use Array.prototype.forEach() for iteration througt the array and assembling the objects and push it to the wanted results.
The forEach() method executes a provided function once per array element.
var array = [{ "_id": 1, "name": "someName", "colorName": "Pink" }, { "_id": 2, "name": "someName2", "colorName": "RoyalBlue" }, { "_id": 3, "name": "aThirdOne", "colorName": "Gold" }, { "_id": 4, "name": "oneMore", "colorName": "LightGreen" }],
result1 = [],
result2 = [];
array.forEach(function (a) {
result1.push({ value: a._id, label: a.name });
var o = {};
o[a._id] = a.name
result2.push(o);
});
document.write('<pre>' + JSON.stringify(result1, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(result2, 0, 4) + '</pre>');
use:
var newObject = _.map(yourObject, function(val) {
return {
"value": val._id,
"label": val.name
}});
And the same concept for the other result you're interested in .

mongodb update on JSON array

I have this data in Mongo:
{'_id':1,
'name':'Root',
'taskId':1,
'parentId':"",
'path':[1],
'tasks':[ {"taskId":3,parentId:1,name:'A',type:'task'},
{"taskId":4,parentId:1,name:'D',type:'task'},
{"taskId":5,parentId:4,name:'B',type:'task'},
{'type':'project' , 'proRef':2},
{"taskId":6,parentId:3,name:'E',type:'task'},
{"taskId":7,parentId:6,name:'C',type:'task'}]
}
Now I want to update taskId 6 with new Json data .
var jsonData = {"taskId":6,"name":'Sumeet','newField1':'Val1','newField2':'Val2'}
query should update if field is available else add new key to existing .Output Like
{"taskId":6,parentId:3,name:'Sumeet',type:'task','newField1':'Val1','newField2':'Val2'}]
I have tried few query but it is completely replacing json .
db.projectPlan.update({_id:1,'tasks.taskId':6},{$set :{'tasks.$':jsonData }});
Thanks in advance for your helps!
Sumeet
You need to transform the jsonData variable into something that can be passed to update. Here's an example that does exactly what you want with your sample document:
var updateData = {};
for (f in jsonData) {
if (f != "taskId") updateData["tasks.$."+f]=jsonData[f];
};
db.projectPlan.update({_id:1, 'tasks.taskId':6}, {$set:updateData})
Result:
{ "_id" : 1,
"name" : "Root",
"taskId" : 1,
"parentId" : "",
"path" : [ 1 ],
"tasks" : [
{ "taskId" : 3, "parentId" : 1, "name" : "A", "type" : "task" },
{ "taskId" : 4, "parentId" : 1, "name" : "D", "type" : "task" },
{ "taskId" : 5, "parentId" : 4, "name" : "B", "type" : "task" },
{ "type" : "project", "proRef" : 2 },
{ "taskId" : 6, "parentId" : 3, "name" : "Sumeet", "type" : "task", "newField1" : "Val1", "newField2" : "Val2" },
{ "taskId" : 7, "parentId" : 6, "name" : "C", "type" : "task" }
] }
You will need to merge the document manually:
var jsonData = {"taskId":5,"name":'Sumeet','newField1':'Val1','newField2':'Val2'};
db.projectPlan.find({ _id: 1 }).forEach(
function(entry) {
for (var taskKey in entry.tasks) {
if (entry.tasks[taskKey].taskId === jsonData.taskId) {
printjson(entry.tasks[taskKey]);
for (var taskSubKey in jsonData) {
entry.tasks[taskKey][taskSubKey] = jsonData[taskSubKey];
}
printjson(entry.tasks[taskKey]);
}
}
db.projectPlan.save(entry);
}
);
Obviously you can leave away the printjson statements. This is simply to see that the merging of the original tasks with the new tasks works. Note that this query will only update a single document as long as the _id field is unique.

Categories

Resources