How to remove empty object in array? - javascript

I am trying to remove the empty object {} from the below structure.
data = [{
"total" : "value",
"status" : "statusVal",
"recs" : [{
"total" : "value",
"region" : "name",
"recs" : [{},{
"recs" : [{
"recs" : [{
"value" : "a",
"label" : "fn"
}]
}]
}]
}]
}]
This is my JavaScript code where I process the data and trying to remove the empty object from the result.
var result = json.parse(data);
for(var i=0;i<result.length;i++){
if(result[i].hasOwnProperty("recs")){
var fset = result[i].recs;
for(var j=0;j<fset.length;j++){
if(fset[j].recs === undefined || fset[j].recs === null){
delete fset[j].recs;
}
if(fset[j].hasOwnProperty("recs")){
var sset = fset[i].recs;
for(var k=0;k<sset.length;k++){
var tset = sset[i].recs;
if(sset[k].hasOwnProperty("recs")){
for(var z=0;z<tset.length;z++){
if(tset[z].hasOwnProperty("recs")){
// logic to push
}
}
}
}
}
}
}
}
I tried checking null and undefined and also with property check bool as false. Since the empty {} is always returning length as 1, that is also ruled out. I am stuck here on processing the removal of empty object.
Above code is removing the entire recs node. Can you help me find what I am missing?

Check the length of the Object.keys() to see if object is empty or not.
Object.keys(fset[j].recs).length === 0
You can't iterate all the dynamic levels of array manually, so better to write the function which has recursive function call.
var data = [{
"total": "value",
"status": "statusVal",
"recs": [{
"total": "value",
"region": "name",
"recs": [{}, {
"recs": [{
"recs": [{
"value": "a",
"label": "fn"
}]
}]
}]
}]
}]
function removeEmpty(ary) {
ary.forEach((item, index) => {
if (Object.keys(item).length === 0) { ary.splice(index, 1); }
else if (item.recs && item.recs.length > 0)
removeEmpty(item.recs)
});
}
removeEmpty(data)
console.log(data)

Related

Convert array of objects into lowercase

Array looks like this:
"myTags":
[{
"type":"one",
"value":"Testing",
"note":"Hey"
},{
"type":"two",
"value":"Yg5GE",
"note":"hey2"
}]
I need to convert type:'one' value 'Testing' into lowercase i.e. value = Testing needs to be 'testing'. Is there a way to so this keeping the same structure?
Note: "type":"one","value":"Testing", may not always be included in the array. So I guess in this scenario I first need to do a check if they exist?
I have tried .map, however I am unable to get the result I want. Any help would be appreciated.
Ideal structure:
"myTags":
[{
"type":"one",
"value":"testing",
"note":"hey"
},{
"type":"two",
"value":"Yg5GE",
"note":"hey2"
}]
Iterate over the elements in myTags, check if type is "one" and only then change the content of value to lowercase (if present)
var data = {
"myTags": [{
"type": "one",
"value": "Testing",
"note": "Hey"
}, {
"type": "one",
"note": "Hey"
}, {
"type": "two",
"value": "Yg5GE",
"note": "hey2"
}]
};
data.myTags.forEach(function(tag) {
if (tag.type === "one" && typeof tag.value !== "undefined") {
tag.value = tag.value.toLowerCase();
}
});
console.log(data.myTags);
You may also first filter the content of myTags to get the element(s) with "type": "one" and only iterate over those element(s)
var data = {
"myTags": [{
"type": "one",
"value": "Testing",
"note": "Hey"
}, {
"type": "one",
"note": "Hey"
}, {
"type": "two",
"value": "Yg5GE",
"note": "hey2"
}]
};
data.myTags
.filter(function(tag) {
return tag.type === "one";
})
.forEach(function(tag) {
if (typeof tag.value !== "undefined") {
tag.value = tag.value.toLowerCase();
}
});
console.log(data.myTags);
This one works perfectly
$(document).ready(function(){
var objects ={"myTags":
[{"type":"one","value":"Testing", "note":"Hey"}
,{ "type":"two", "value":"Yg5GE", "note":"hey2"}]};
var obj = objects.myTags.map(function(a) {
a.value = a.value.toLowerCase();
return a;
});
console.log(obj);
});
output:
{type: "one", value: "testing", note: "Hey"}
{type: "two", value: "yg5ge", note: "hey2"}
Thank you
Achieve this very simply by using an arrow function and the map() method of the Array
var words = ['Foo','Bar','Fizz','Buzz'].map(v => v.toLowerCase());
console.log(words);

Filter object by array of ids

I have a list of objects. On each object I have an array.
Example:
"-KpvPH2_SDssxZ573OvM" : {
"date" : "2017-07-25T20:21:13.572Z",
"description" : "Test",
"id" : [ {
0: "0a477fed-8944-9f5d-56fd-c95fe7663a07",
1: "0a477fed-8944-9f5d-56fd-c95fe7663a08"
} ]
},
"-KpvPLSfotrZiBDeVOxU" : {
"date" : "2017-07-25T20:21:33.159Z",
"description" : "Test 2",
"id" : [ {
0: "6e79eadd-21b5-91cc-4b71-7ac1a42278b1"
} ]
}
How do I search for an object using the ID array as a parameter?
When I need to filter only one array I use filter and everything works ok.
var result = $.grep(items, function(e){ return e.id == id; });
But in this case I believe it does not work.
Thanks
Since the ID's are a little deeper in the object, and they are part of an object, I think a better approach (as compared to $.grep) would be a custom filter. Here I have assumed you want exact comparison while filtering, based on your question. But you could easily have partial comparison with indexOf as well.
var data = {
"-KpvPH2_SDssxZ573OvM": {
"date": "2017-07-25T20:21:13.572Z",
"description": "Test",
"id": [{
0: "0a477fed-8944-9f5d-56fd-c95fe7663a07",
1: "0a477fed-8944-9f5d-56fd-c95fe7663a08"
}]
},
"-KpvPLSfotrZiBDeVOxU": {
"date": "2017-07-25T20:21:33.159Z",
"description": "Test 2",
"id": [{
0: "6e79eadd-21b5-91cc-4b71-7ac1a42278b1"
}]
}
};
//console.log(data);
var inputID = "0a477fed-8944-9f5d-56fd-c95fe7663a08";
var filteredData = [];
for (var prop in data) {
if(data.hasOwnProperty(prop)) {
var item = data[prop];
var itemIDs = item.id[0];
for(var id in itemIDs) {
if (itemIDs[id] == inputID) {
filteredData.push(item);
}
}
}
}
console.log(filteredData);

convert integer to array of object.

var items = [
{ "id": 1, "label": "Item1" },
{ "id": 2, "label": "Item2" },
{ "id": 3, "label": "Item3" }
];
I have this array of objects named 'items'. I get itemselected = 3 from the database.
I need to convert this 3 into the following form.
0:Object
id:3
label:"Item3"
Similarly, if i have a value 2 coming from the database, i should convert it to
0:Object
id:2
label:"Item2"
Can anyone please let me hint of how to get it solved. i am not here to get the answer. These questions are quite tricky for me and i always fail to get the logic right. Any advice on how to master this conversions will be of great help. thanks.
Since you tagged underscore.js, this should be very easy:
var selectedObject = _.findWhere(items, {id: itemselected});
Using ECMA6, you can achieve the same using .find method on arrays:
let selectedObject = items.find(el => el.id === itemselected);
With ECMA5, you can use filter method of arrays. Be careful that filter returns undefined if no element has been found:
var selectedObject = items.filter(function(el) { return el.id === itemselected});
Use jquery $.map function as below
$.map(item, function( n, i ) { if(n["id"] == 3) return ( n );});
Based on the title of your question: «convert integer to array of object». You can use JavaScript Array#filter.
The filter() method creates a new array with all elements that
pass the test implemented by the provided function.
Something like this:
var items = [{
"id": 1,
"label": "Item1"
},
{
"id": 2,
"label": "Item2"
},
{
"id": 3,
"label": "Item3"
}
];
var value = 2;
var result = items.filter(function(x) {
return x.id === value;
});
console.log(result); // Prints an Array of object.
Try this
var obj = {} ;
items = [
{ "id": 1, "label": "Item1" },
{ "id": 2, "label": "Item2" },
{ "id": 3, "label": "Item3" }
];
items.map(function(n) { obj[n.id] = n });

How can I reference this data in this JSON file?

I am using d3.js's "d3.json(); function to reach out and fetch some data from a REST API.
The data comes back as this:
{
"offset" : 0,
"rows": [
{ "_id":
{ "$oid" : "1234567" },
"mockupData" : [ {
"Analysis" : "Test",
"Description" : "The Test indicates...",
"Data" : [
{ "Category" : "A",
"Statistic" : 0.15,
"Value" : 0.95 },
{ "Category" : "B",
"Statistic" : 0.65,
"Value" : 0.85 },
] } ] }
],
"total_rows" : 1 ,
"query" : {} ,
"millis" : 0
}
I am having an extremely difficult time drilling down in to the json to get what I want.
I'm attempting to set it up like this:
function generateChart(){
var chart;
var Category = [{key:"Stuff", values:[]}];
d3.json('http://url_that_returns_json/', function(error,data{
for(var key in data._SOMETHING_){
switch(key){
case "A":
Category[0] ["values"].push({"label":"Statistic","value""data.Category[key]});
... // same for B
})
// more graph logic
I appear to be missing some entire fragment of knowledge on this. Guidance? Help?
Thanks in advance.
Here is a fiddle I have implemented : https://jsfiddle.net/thatOneGuy/486mwb86/1/
First off, I set the data as a variable so I can use it later. So :
var data = {
"offset": 0,
"rows": [{
"_id": {
"$oid": "1234567"
}, ... //and so on
This is exactly the same as you using :
d3.json('http://url_that_returns_json/', function(error,data{
Both data variables are the same.
Then I got to the point you wanted to check, i.e the categories in the data attribute, like so :
var thisDataSet = data.rows[0].mockupData[0].Data;
As this is an array and not an object, I used a for loop to loop through :
for (var i = 0; i < thisDataSet.length; i++) {
And, in my opinion, you didn't need a switch statement as it looks like you just wanted to populate Category.values with the different categories. So I just pushed the current value of the category in the dataset to this Category.values :
Category[0]["values"].push({
"label": "Statistic",
"value": thisDataSet[i].Category //push category here
});
And that's it. Check the console log for output. Should work fine. Full function :
function generateChart() {
var chart;
var Category = [{
key: "Stuff",
values: []
}];
console.log(data.rows[0].mockupData[0].Data)
var thisDataSet = data.rows[0].mockupData[0].Data;
for (var i = 0; i < thisDataSet.length; i++) {
//for (var key in data.rows[0].mockupData[0].Data) {
console.log(thisDataSet[i])
Category[0]["values"].push({
"label": "Statistic",
"value": thisDataSet[i].Category
});
}
console.log(Category)
}

How to loop json array to get key and value in javascript?

I have below json array structure.. How can i get the key and value of each of the records json object?
{
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}
My expected output is to get the key and value... below as example:
<b>key</b> : cf_1, <b>value</b> : Clinic San
I have tried to loop in the records, but since i don't know the key, so i unable to get the value..
for (var z in records)
{
var value = records[z].cf_1;
alert(value);
}
//i don't know the key here.. i want to get the key and value
The full JSON structure is as below:
{
"forms": [{
"id": 1,
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}, {
"id": 7,
"records": [{
"cf_31": "27/3/2016",
"cf_32": "Singapore",
"cf_33": "dfd555",
"cfe_34": ""
}]
}, {
"id": 11,
"records": [{
"cfsub_10": "9",
"cf_9": "25/3/2016",
"cf_10": "256.50",
"cfe_11": "dfg44"
}]
}]
}
Hope this one is helpful for you.
$.each(value.forms, function(index,array){
$.each(array.records, function(ind,items){
$.each(items, function(indo,itemso){
alert( "Key -> "+indo + " : values -> " + itemso );
});
});
});
var getKeys = function (arr) {
var key, keys = [];
for (i = 0; i < arr.length; i++) {
for (key in arr[i]) {
if (arr[i].hasOwnProperty(key)) {
keys.push(key);
}
}
}
return keys;
};

Categories

Resources