Remove Object from "Object of Objects" - javascript

I have a Object that contain objetcs like this.Object {MAILING ADDRESS: "P O BOX 59", APN: "066-102-11-1"} . Now I need data without empty Object. Like I get output like this Output
Object {MAILING ADDRESS: "P O BOX 59", APN: "066-102-11-1"}
Object {MAILING ADDRESS: "", APN: ""}
Object {MAILING ADDRESS: "P O BOX 3", APN: "066-105-11-1"}
Object {MAILING ADDRESS: "", APN: ""}
So in this case I dont want to get 2nd and 4th object. And in case of 100 I dont want to get 2,4,6,8..100 index . Because output after one time is repeating and I have to remove this. ScreenShot of output I getting
//Code How I am creating this
ExportTool.prototype.click = function(value) {
var lidtest = mapport.panels.info.current.selection.features.mem;
if (value != undefined) {
var lid = lidtest[value].attributes.layer_id;
} else {
var lid = lidtest[0].attributes.layer_id;
}
if (!lid) return;
var tbody;
var thead;
tbody = $('<tbody></tbody>');
thead = $('<thead></thead>');
self = this;
// Reset
this.tblHeader = [];
this.tblData = [];
this.labelData = [];
// thead.children().remove();
// tbody.children().remove();
//var tbody;
var layer = mapport.layer(lid);
var tr = $('<tr></tr>');
layer.fields.each(function(field) {
tr.append($('<th ></th>').text(field.name));
// Table heading for the PDF
if (self.availableForTable.indexOf(field.name.toUpperCase()) != -1)
self.tblHeader.push(field.name);
});
tbody.append(tr);
var features = mapport.panels.info.current.features();
for (var i = 0; i < features.length; ++i) {
if (features[i].geometry != null) {
var data = features[i].attributes.data,
row_data = [],
row_field, obj_field = {};
tr = $('<tr></tr>');
layer.fields.each(function(field) {
var field_name = field.name.toUpperCase();
var td = $('<td></td>');
if (data[field.id] != null) td.text(data[field.id]);
tr.append(td);
if (self.availableForTable.indexOf(field_name) != -1) {
row_field = (data[field.id] != null) ? data[field.id] : '';
row_data.push(row_field);
obj_field[field_name] = row_field;
}
});
row_data = row_data.filter(function(entry) {
return /\S/.test(entry);
});
obj_field = JSON.parse(obj_field);
console.log(obj_field);
// Table Data for the PDF
this.tblData.push(row_data);
// Table Data for the PDF
this.labelData.push(obj_field);
tbody.append(tr);
$('#table_multi_layers').append(tbody);
}
}
}

You can use filter option like this. You can change your object to array and apply filter.
var someArray = $.map(obj_field, function(value, index) {
return [value];
});
someArray = [{
MAILINGADDRESS: "P O BOX 59",
APN: "066-102-11-1"
},
{
MAILINGADDRESS: "",
APN: ""
},
{
MAILINGADDRESS: "P O BOX 59",
APN: "066-102-11-1"
}, {
MAILINGADDRESS: "",
APN: ""
}
];
result = someArray.filter(function(el) {
return el.APN !== "";
});
console.log(JSON.stringify(result, null, ' '));

Related

Using jQuery, how do I select dynamic related data keys on an element and output them into an array?

For example, given this HTML:
<div class="playlist"
data-name1="Some Name 1"
data-value1="123"
data-name2="Some Name 2"
data-value2="456"
data-name3="Some Name 3"
data-value3="789"
></div>
I want to return an array of key/value pairs like so (using jQuery):
[{
"name": "Some Name 1",
"value": "123"
}, {
"name": "Some Name 2",
"value": "456"
}, {
"name": "Some Name 3",
"value": "789"
}]
Here is some pseudo code that I thought about but obviously doesn't work:
array = []
$(".playlist").attr("data-name-*, data-value-*").each(function(name, value){
array.push({"name": name, "value": value});
}
})
return array;
Any ideas?
array = []
$.each($('.playlist')[0].attributes, function(i, attrib){
array.push({name : attrib.name, value : attrib.value});
});
console.log(array);
This can give you something to work with. It works.
var attributes = $('.playlist')[0].attributes;
var total_attr = attributes.length - 1;
var test = [];
for (var i = 1; i < attributes.length; i += 2) {
var attr = attributes[i];
var value = attributes[i+1];
var temp = {};
temp['name' + i] = attr.nodeValue;
temp['value' + i] = value.nodeValue;
test.push(temp)
}
console.log(test)
var length_data = Object.keys($(".playlist").data()).length/2;
var data = []
for (i = 1; i <= length_data; i++) {
data.push({"name" : $(".playlist").attr('data-name'+i), "value" : $(".playlist").attr('data-value'+i)} )
}
DEMO here
Update
For prevent when u had more data :
var length_data = Object.keys($(".playlist").data()).length/2;
var data = []
for (i = 1; i <= length_data; i++) {
if (typeof $(".playlist").attr('data-name'+i) == "undefined" || typeof $(".playlist").attr('data-value'+i) == "undefined" ) continue;
data.push({"name" : $(".playlist").attr('data-name'+i), "value" : $(".playlist").attr('data-value'+i)} )
}
Demo update

Javascript: group JSON objects using specific key

I have the following JSON object and wanted to merge them by OrderID, making the items into array of objects:
[
{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
},
{
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}
]
and I'm wondering how in Javascript to merge the items on the same order...like this:
[{
"OrderID": "999123",
"Items": [{
"ItemCode": "DY-FBBO",
"ItemQuantity": "2",
"ItemName": "DOIY Foosball Bottle Opener > Red",
"ItemPrice": "34.95"
}, {
"ItemCode": "TED-072",
"ItemQuantity": "1",
"ItemName": "Ted Baker Womens Manicure Set",
"ItemPrice": "74.95"
}]
}]
I suggest you use javascript library like underscorejs/lazyjs/lodash to solve this kind of thing.
Here is the example on using underscorejs:
var data = [{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
}, {
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}]
var result = _.chain(data).groupBy(function (e) {
return e.OrderID;
}).map(function (val, key) {
return {
OrderID: key,
Items: _.map(val, function (eachItem) {
delete eachItem.OrderID;
return eachItem;
})
};
}).value();
Working example:
var data = [{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
}, {
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}];
var result = _.chain(data).groupBy(function (e) {
return e.OrderID;
}).map(function (val, key) {
return {
OrderID: key,
Items: _.map(val, function (eachItem) {
delete eachItem.OrderID;
return eachItem;
})
};
}).value();
document.write(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
This should do what you want it to do, but it's rather a group function than a merge function :)
You can see the result in the browser console.
var items = [
{
"OrderID":"999123",
"ItemCode":"TED-072",
"ItemQuantity":"1",
"ItemPrice":"74.95",
},
{
"OrderID":"999123",
"ItemCode":"DY-FBBO",
"ItemQuantity":"2",
"ItemName":"DOIY Foosball Bottle Opener > Red",
"ItemPrice":"34.95",
}
];
function groupBy(ungrouped, groupByProperty) {
var result = [],
getGroup = function (arr, val, groupByProperty) {
var result, j, jlen;
for (j = 0, jlen = arr.length; j < jlen; j++) {
if (arr[j][groupByProperty] === val) {
result = arr[j];
break;
}
}
if (!result) {
result = {};
result.items = [];
result[groupByProperty] = val;
arr.push(result);
}
return result;
}, i, len, item;
for (i = 0, len = ungrouped.length; i < len; i++) {
item = getGroup(result, ungrouped[i][groupByProperty], groupByProperty);
delete ungrouped[i][groupByProperty];
item.items.push(ungrouped[i]);
}
return result;
}
var grouped = groupBy(items, 'OrderID');
document.getElementById('result').innerHTML = JSON.stringify(grouped);
console.log(grouped);
<div id="result"></div>
Lodash is a great Javascript Utility library that can help you in this case. Include the latest version of lodash in your code and group the objects like this:
var mergedOrders = _.groupBy(OriginalOrders, 'OrderID');
It seems you'll have to do a function that, for each entry, will check if it match
try this :
// your array is oldArr
var newArr = []
for (var i=0;i<oldArr.length;i++){
var found = false;
for(var j=0;j<newArr.length;j++){
if(oldArr[i]["OrderID"]==newArr[j]["OrderID"]){
newArr[j]["Items"].push(oldArr[i]);
found=true;
break;
}
if(!found){
newArr.push({"OrderID" : oldArr[i]["OrderID"], "Items" : oldArr[i]});
}
}
You need to loop and create new grouped objects according to your requirement.
For an easier approach I would suggest using jquery-linq
var qOrderIds = $.Enumerable.From(myArray).Select(function(item) { return item.OrderID; }).Distinct();
var groupedList = qOrderIds.Select(function(orderId) {
return {
OrderID: orderId,
Items : $.Enumerable.From(myArray).Where(function(item) { item.OrderID === orderId}).ToArray()
};
}).ToArray();
Thank you for all your answers.
I was able to attain my goal (maybe a bit dirty and not as beautiful as yours but it worked on my end). Hoping this might help others in the future:
function processJsonObj2(dataObj, cfg) {
var retVal = dataObj.reduce(function(x, y, i, array) {
if (x[cfg.colOrderId] === y[cfg.colOrderId]) {
var orderId = x[cfg.colOrderId];
var addressee = x[cfg.colAddressee];
var company = x[cfg.colCompany];
var addr1 = x[cfg.colAddress1];
var addr2 = x[cfg.colAddress2];
var suburb = x[cfg.colSuburb];
var state = x[cfg.colState];
var postcode = x[cfg.colPostcode];
var country = x[cfg.colCountry];
var orderMsg = x[cfg.colOrderMessage];
var carrier = x[cfg.colCarrier];
delete x[cfg.colOrderId];
delete y[cfg.colOrderId];
delete x[cfg.colAddressee];
delete y[cfg.colAddressee];
delete x[cfg.colCompany];
delete y[cfg.colCompany];
delete x[cfg.colAddress1];
delete y[cfg.colAddress1];
delete x[cfg.colAddress2];
delete y[cfg.colAddress2];
delete x[cfg.colSuburb];
delete y[cfg.colSuburb];
delete x[cfg.colState];
delete y[cfg.colState];
delete x[cfg.colPostcode];
delete y[cfg.colPostcode];
delete x[cfg.colCountry];
delete y[cfg.colCountry];
delete x[cfg.colOrderMessage];
delete y[cfg.colOrderMessage];
delete x[cfg.colCarrier];
delete y[cfg.colCarrier];
var orderObj = {};
orderObj[cfg.colOrderId] = orderId;
orderObj[cfg.colAddressee] = addressee;
orderObj[cfg.colCompany] = company;
orderObj[cfg.colAddress1] = addr1;
orderObj[cfg.colAddress2] = addr2;
orderObj[cfg.colSuburb] = suburb;
orderObj[cfg.colState] = state;
orderObj[cfg.colPostcode] = postcode;
orderObj[cfg.colCountry] = country;
orderObj[cfg.colOrderMessage] = orderMsg;
orderObj[cfg.colCarrier] = carrier;
orderObj["Items"] = [ x, y ];
return orderObj;
} else {
var orderId = x[cfg.colOrderId];
var addressee = x[cfg.colAddressee];
var company = x[cfg.colCompany];
var addr1 = x[cfg.colAddress1];
var addr2 = x[cfg.colAddress2];
var suburb = x[cfg.colSuburb];
var state = x[cfg.colState];
var postcode = x[cfg.colPostcode];
var country = x[cfg.colCountry];
var orderMsg = x[cfg.colOrderMessage];
var carrier = x[cfg.colCarrier];
var itemCode = x[cfg.colItemCode];
var itemQuantity = x[cfg.colItemQuantity];
var itemName = x[cfg.colItemName];
var itemPrice = x[cfg.colitemPrice];
var item = {};
item[cfg.colItemCode] = itemCode;
item[cfg.colItemQuantity] = itemQuantity;
item[cfg.colItemName] = itemName;
item[cfg.colItemPrice] = itemPrice;
var orderObj = {};
orderObj[cfg.colOrderId] = orderId;
orderObj[cfg.colAddressee] = addressee;
orderObj[cfg.colCompany] = company;
orderObj[cfg.colAddress1] = addr1;
orderObj[cfg.colAddress2] = addr2;
orderObj[cfg.colSuburb] = suburb;
orderObj[cfg.colState] = state;
orderObj[cfg.colPostcode] = postcode;
orderObj[cfg.colCountry] = country;
orderObj[cfg.colOrderMessage] = orderMsg;
orderObj[cfg.colCarrier] = carrier;
orderObj["Items"] = [ item ];
return orderObj;
}
});
return retVal;
}

Efficient function for creating JSON data from File Directory Structure?

Like the title says, I have a directory structure, I want to convert it into a JSON format compatible for jsTree usage.
So the output for a given list
INPUT:
./Simple Root Node
./Root Node 2
./Root Node 2/Child 1
./Root Node 2/Child 2
OUTPUT:
treeJSON = [
{ "id" : "ajson1", "parent" : "#", "text" : "Simple root node" },
{ "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
{ "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" },
]
My Method:
Currently, I'm taking each line from the input. Say ./Root Node 2/Child 1, then I pattern match the first folder, creating an array like { "id" : "ajson2", "parent" : "#", "text" : "Root node 2" }. Then go recursively for the next removing the first folder.Hence, creating the net array as { "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" }.
I do this for each line in the input and then use my unique array function as in http://jsfiddle.net/bsw5s60j/8/ to strip all the duplicate arrays which were created. For instance, { "id" : "ajson2", "parent" : "#", "text" : "Root node 2" } would be created twice. Once while going through the 3rd line and then the 4th line.
Clearly, this code is HIGHLY inefficient.If I have around 1.3K directories, then assume each has 4 sub directories, we have 5.2K arrays which have to be checked for duplicates.
This is creating a hge problem. Is there any other efficient way I can twaek this code?
Fiddle: (Works with Chrome Only because of the file webkit attribute) http://jsfiddle.net/bsw5s60j/8/
Javascript
var input = document.getElementById('files');
var narr = [];
var fileICON = "file.png";
//when browse button is pressed
input.onchange = function (e) {
var dummyObj = [];
var files = e.target.files; // FileList
for (var i = 0, f; f = files[i]; ++i) {
var fname = './' + files[i].webkitRelativePath;
narr = $.merge(dummyObj, (cat(fname)));
}
treeJSON = narr.getUnique(); // getting the JSON tree after processing input
console.log(JSON.stringify(treeJSON));
//creating the tree using jstree
$('#tree')
.jstree({
'core': {
'check_callback': true,
'data': function (node, cb) {
cb.call(this, treeJSON);
}
}
});
var tree = $('#tree').jstree(true);
tree.refresh();
};
//get unqiue array function
Array.prototype.getUnique = function () {
var o = {}, a = [];
for (var i = 0, l = this.length; i < l; ++i) {
if (o.hasOwnProperty(JSON.stringify(this[i]))) {
continue;
}
a.push(this[i]);
o[JSON.stringify(this[i])] = 1;
}
return a;
};
// categorizing function which converts each ./Files/Root/File.jpg to a JSON
var objArr = [];
var folderArr = [];
function cat(a) {
if (!a.match(/\/(.+?)\//)) {
var dummyObj = {};
var fname = a.match(/\/(.*)/)[1];
dummyObj.id = fname;
dummyObj.text = fname;
if (folderArr === undefined || folderArr.length == 0) {
dummyObj.parent = '#';
} else {
dummyObj.parent = folderArr[(folderArr.length) - 1];
dummyObj.icon = fileICON; // add extention and icon support
}
objArr.push(dummyObj);
return objArr;
} else {
if (a.charAt(0) == '.') {
var dummyObj = {};
var dir1 = a.match(/^.*?\/(.*?)\//)[1];
dummyObj.id = dir1;
dummyObj.text = dir1;
dummyObj.parent = '#';
dummyObj.state = {
'opened': true,
'selected': true
}; // not working
folderArr.push(dir1);
objArr.push(dummyObj);
var remStr = a.replace(/^[^\/]*\/[^\/]+/, '');
cat(remStr);
return objArr;
} else {
var dummyObj = {};
var dir1 = a.match(/^.*?\/(.*?)\//)[1];
dummyObj.id = dir1;
dummyObj.text = dir1;
dummyObj.parent = folderArr[(folderArr.length) - 1];
folderArr.push(dir1);
objArr.push(dummyObj);
var remStr = a.replace(/^[^\/]*\/[^\/]+/, '');
cat(remStr);
return objArr;
}
}
}
HTML
<input type="file" id="files" name="files[]" multiple webkitdirectory />
<div id="tree"></div>
Any changes or suggestions would be greatly helpful! Thanks
Here is a simple algorithm that should do quite efficiently, using a map from filepaths to their ids:
var idcount = 0;
var treeJSON = [];
var idmap = {};
function add(dirs) {
if (!dirs.length) return "#";
var name = dirs.join("/");
if (name in idmap)
return idmap[name];
var dir = dirs.pop();
var parent = add(dirs);
var id = "ajson" + ++idcount;
treeJSON.push({id: id, parent: parent, text: dir});
return idmap[name] = id;
}
var files = e.target.files; // FileList
for (var i=0; i<files.length; ++i) {
var name = files[i].webkitRelativePath;
add(name.split("/"));
}
return treeJSON;
(updated jsfiddle demo)
This is how you might use it for dynamic updates:
// initalise JStree here
var idcount = 0;
var treeJSON = [];
var idmap = {};
function add(dirs, isfolder) {
if (!dirs.length) return "#";
var name = dirs.join("/");
if (name in idmap) {
if (isfolder && idmap[name].icon)
delete idmap[name].icon;
return idmap[name];
}
var dir = dirs.pop();
var parent = add(dirs, true);
var id = "ajson" + ++idcount;
var item = {id: id, parent: parent, text: dir}
if (parent == "#")
item.state = {opened:true, selected:true};
if (!isfolder && dir.indexOf(".") > 0)
item.icon = fileICON;
treeJSON.push(item);
return idmap[name] = id;
}
input.onchange = function(e) {
var files = e.target.files; // FileList
for (var i=0; i<files.length; ++i) {
var name = files[i].webkitRelativePath;
add(name.split("/"), false);
}
// refresh JStree
};

javascript - match defined tags present in a string

I defined some tags in an array:
var myArray = [
"mouse",
"common",
"malcom",
"mountain",
"melon",
"table"
];
Now I want to extract my defined tags from a string, for example
from the string: the mouse is on the desk, I want to extract the "mouse" tag
or from the string the mouse is on the table, I want to extract the tags "mouse" and "table"
This code partially works, but there is some problem:
var myArray = [
"mouse",
"common",
"malcom",
"mountain",
"melon",
"table"
];
Object.defineProperty(Array.prototype, "MatchInArray", {
enumerable: false,
value: function(value) {
return this.filter(function(currentItem) {
return currentItem.match(value);
});
}
});
function doSearch(text){
out = myArray.filter(function(currentItem){
return currentItem.toLowerCase().indexOf(text) !== -1;
});
return out;
}
myInput.oninput = function(){
var XXX = this.value;
var YYY = XXX.replace(/ /g,',');
var ZZZ = YYY.split(',');
for(var i=0; i<ZZZ.length; i++){
output.innerHTML = doSearch(ZZZ[i]);
}
//output.innerHTML = doSearch(this.value);
};
What I'm doing wrong?
DEMO
Flip the comparison of text to item so that you don't have to do all that regex and splitting:
function doSearch(text){
out = myArray.filter(function(currentItem){
return text.toLowerCase().indexOf(currentItem) !== -1;
});
return out;
}
myInput.oninput = function(){
output.innerHTML = doSearch(this.value);
};

change the json structure after getting data

I am getting a json data having structure
{
SearchDAO: [
{
PERSONADDRESS_H_ADDRESS_LINE_ONE: "599 Waterloo place",
PERSON_H_BIRTHDATE_VALUE: "1939-01-11 00:00:00",
PERSON_H_CREATE_TS: "2012-11-22 11:17:13.879",
PERSON_H_GENDER_CD: "M"
}
]
}
As you can see in the data set two type of keys are there
1. starting with "PERSONADDRESS"
2. starting with "PERSON"
I have to convert this structure to
{
"PERSON":[
{
H_BIRTHDATE_VALUE: "1939-01-11 00:00:00",
H_CREATE_TS: "2012-11-22 11:17:13.879",
H_GENDER_CD: "M"
}
],
"PERSONADDRESS":[
{
H_ADDRESS_LINE_ONE: "599 Waterloo place"
}
]
I am struggling to do this.
As It need to splice key string and change the structure
Please help
I am trying something like this
$.each(data.SearchDAO[0], function(k, v) {
var streetaddress= k.substr(0, k.indexOf('_'));
console.log(streetaddress)
if(returnVar[streetaddress] == undefined){
thisItem = [];
returnVar[streetaddress] = thisItem;
}
else {
thisItem = returnVar[streetaddress];
}
var obj = {};
obj.issueValue = v;
thisItem.push(obj);
});
console.log(thisItem)
I solved the problem
here is my code
returnVar={};
$.each(data.SearchDAO[0], function(k, v) {
var streetaddress= k.substr(0, k.indexOf('_'));
var keyFinal= k.substr(k.indexOf('_')+1,k.length-1);
console.log(keyFinal)
if(returnVar[streetaddress] == undefined){
thisItem = {};
returnVar[streetaddress] = thisItem;
thisItem[keyFinal]=v;
}
else {
thisItem = returnVar[streetaddress];
thisItem[keyFinal]=v;
}
});
console.log(returnVar)
This should do it (for multiple persons as well):
var json = {
SearchDAO: [
{
PERSONADDRESS_H_ADDRESS_LINE_ONE: "599 Waterloo place",
PERSON_H_BIRTHDATE_VALUE: "1939-01-11 00:00:00",
PERSON_H_CREATE_TS: "2012-11-22 11:17:13.879",
PERSON_H_GENDER_CD: "M"
},
{
PERSONADDRESS_H_ADDRESS_LINE_ONE: "123 Place",
PERSON_H_BIRTHDATE_VALUE: "1901-01-01 00:00:00",
PERSON_H_CREATE_TS: "2001-01-01 00:00:00.000",
PERSON_H_GENDER_CD: "F"
}
]
}
var converted = {};
for (var i = 0; i < json.SearchDAO.length; i++)
{
var row = json.SearchDAO[i];
var keys = Object.keys(row);
for (var j = 0; j < keys.length; j++)
{
var key = keys[j];
var key_prefix = key.substr(0, key.indexOf('_'));
var key_suffix = key.substr(key.indexOf('_') + 1);
if (!(key_prefix in converted)) converted[key_prefix] = [];
if (!(i in converted[key_prefix])) converted[key_prefix][i] = {};
converted[key_prefix][i][key_suffix] = row[key_prefix + "_" + key_suffix];
}
}

Categories