How to loop json array to get key and value in javascript? - 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;
};

Related

How to remove empty object in array?

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)

Evaluating key values in multi-dimensional object

I have a multi-dimensional object that looks like this:
{
"links": [{"source":"58","target":"john","total":"95"},
{"source":"60","target":"mark","total":"80"}],
"nodes":
[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
}
I am trying to evaluate the value of "total" in "links." I can do this in a one-dimensional array, like this:
for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (!isNaN(data[i][key])) {
data[i][key] = +data[i][key];
}
}
};
But I have not been able to figure out how to do this in two-dimensions (especially calling the value of key "total" by name).
Can anybody set me on the right track? Thank you!
Starting from the principle that the structure of your array is this, you can to iterate the keys and the values:
var obj = {
"links": [{"source":"58","target":"john","total":"95"},
{"source":"60","target":"mark","total":"80"}],
"nodes":
[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
};
for (var key in obj){
obj[key].forEach(function(item){
for(var subkey in item){
if (subkey == 'total')
console.log(item[subkey]);
};
});
};
You can get total using reduce
check this snippet
var obj = {
"links": [{
"source": "58",
"target": "john",
"total": "95"
}, {
"source": "60",
"target": "mark",
"total": "80"
}, {
"source": "60",
"target": "mark",
"total": "80"
}],
"nodes": [{
"name": "john"
}, {
"name": "mark"
}, {
"name": "rose"
}]
}
var links = obj.links;
var sum = links.map(el => el.total).reduce(function(prev, curr) {
return parseInt(prev, 10) + parseInt(curr, 10);
});
console.log(sum);
Hope it helps
Extract the values from the array, convert them to numbers and add them up.
Array.prototype.map() and Array.prototype.reduce() are pretty helpful here:
var data = {"links":[{"source":"58","target":"john","total":"95"},{"source":"60","target":"mark","total":"80"}], "nodes":[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]};
var sum = data.links.map(function(link) {
return +link.total;
}).reduce(function(a, b) {
return a + b;
});
console.log(sum);

How to get objects with same key values with comma separated

I have an array of objects , each object have key and value .I want if object have same keys then their values shoud be comma sepated of all the values of same key.
my html code:
<p ng-repeat="item in allOptions" class="item" id="{{item.id}}">
{{item.id}} <input type="checkbox" ng-change="sync(bool, item)" ng-model="bool" > {{item}} Selected: {{bool}}
</p>
and my controller code is :
$scope.allOptions = [
{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
];
$scope.data = [
];
$scope.sync = function(bool, item){
if(bool){
// add item
$scope.data.push(item);
} else {
// remove item
for(var i=0 ; i < $scope.data.length; i++) {
if($scope.data[i] == item.id){
$scope.data.splice(i,1);
}
}
}
};
In data array i have objects ,if we select same key of objects (same id value )then i want
{
"id": "1",
"data": "one","two",
}
var myData = [{
"id": "1",
"data": "one",
},{
"id": "1",
"data": "two",
},{
"id": "2",
"data": "three",
}];
var output = [];
//Iterating each element of the myData
myData.forEach(o => {
//Checking the duplicate value and updating the data field
let temp = output.find(x => {
if (x && x.id === o.id) {
x.data += ", " + o.data;
return true;
}
});
if(!temp)
output.push(o);
});
console.log(output);
I think, easiest way to make it would be like:
z = [
{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
];
And immediate code:
var result = {};
var groupedO = {};
for(a in z){
var id = z[a].id;
var data = z[a].data;
if(groupedO[id] && groupedO[id].data){
groupedO[id].data = groupedO[id].data + ',' + data;
} else {
groupedO[id] = {data:data};
}
}
for(ind in groupedO) {
var el = groupedO[ind];
if(el.data.split(',').length > 1) { // here we take only last those, where many datas grouped in
result.id = ind;
result.data = el.data;
}
}
After this, result will look like:
{ id: "1", data: "one,two" }
If you use jQuery, then you can use $.extend() function in this code if you don't want to put reference to the object item in array hash. This means that if you change the object item in array hash, then object item in array myData change too. To avoid this, use $.extend() function.
var myData = [
{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
]; // this will be your input data
function filterData(collection) {
var hash = {};
var result = [];
collection.forEach(function (item) {
if (hash[item.id]) {
hash[item.id].data += ', ' + item.data;
}
else {
hash[item.id] = $.extend({}, item);
}
});
for (var i in hash) {
result.push(hash[i]);
}
return result;
}
var filteredData = filterData(myData); //your filtered data
You can do this in following manner:
var myData = [{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
]; // this will be your input data
function filterData(collection) {
var hash = {};
var result = [];
collection.forEach(function(item) {
if (hash[item.id]) {
hash[item.id].data += ', ' + item.data;
} else {
hash[item.id] = item;
}
});
for (var i in hash) {
result.push(hash[i]);
}
return result;
}
console.log(
filterData(myData) //your filtered data
)

group by/formatting json data in Javascript

Sorry if this has been asked before. I have the JSON structure like:
{"data":[
{"Date":"03/04/2016","Key":"A","Values":"123"},
{"Date":"04/04/2016","Key":"A","Values":"456"},
{"Date":"03/04/2016","Key":"B","Values":"789"},
{"Date":"04/04/2016","Key":"B","Values":"012"}
]}
I want to change this to a different format which is basically grouped by Key and combines rest of the field in Values
{"Result":[
{
"Key":"A"
"Values":[["03/04/2016","123"], ["04/04/2016","456"]]
},
{"Key":"B"
"Values":[["03/04/2016","789"]},["04/04/2016","012"]]
}
]}
I want to do this javascript/html
You could iterate and build a new object if not exist.
var object = { "data": [{ "Date": "03/04/2016", "Key": "A", "Values": "123" }, { "Date": "04/04/2016", "Key": "A", "Values": "456" }, { "Date": "03/04/2016", "Key": "B", "Values": "789" }, { "Date": "04/04/2016", "Key": "B", "Values": "012" }], result: [] };
object.data.forEach(function (a) {
if (!this[a.Key]) {
this[a.Key] = { Key: a.Key, Values: [] };
object.result.push(this[a.Key]);
}
this[a.Key].Values.push([a.Date, a.Values]);
}, Object.create(null));
console.log(object);
I think this can be a better answer (but Nina's answer is the match for your problem terms) if items of data array have different properties and you don't want to change input data.
var raw = {"data":[
{"Date":"03/04/2016","Key":"A","Values":"123"},
{"Date":"04/04/2016","Key":"A","Values":"456"},
{"Date":"03/04/2016","Key":"B","Values":"789"},
{"Date":"04/04/2016","Key":"B","Values":"012"}
]};
var result = new Map;
raw.data.forEach(entry => {
var key = entry.Key;
if (this[key])
return this[key].push(getClonedData(entry));
this[key] = [getClonedData(entry)];
result.set(key, {
Key: key,
Values: this[key]
})
}, Object.create(null));
var filtered = {
result: [...result.values()]
}
console.log(filtered);
function getClonedData(entry) {
data = Object.assign({}, entry);
delete data.Key;
return data;
}

How to iterate through nested objects in a generic way

I am trying to fetch the value of the nested objects without using it's key. Like for example if I have a object like
var a = {"key" : "100"}
I don't want to use a.key, to get the result, though i have nested objects, it is becoming difficult for me to fetch the value this is what I have tried:
var Obj = [{"ghi":{"content":"abc"}},{"def":{"imgURL":"test.png"}},{"abc":{"key":"001"}},{"ghi":{"content":"abc"}},{"def":{"imgURL":"test.png"}},{"abc":{"key":"001"}}]
for(var key in Obj){
abc = Obj[key]
for(var j in abc){
def = abc[key]
}
}
So i need the values of all the objects, without using the key directly.
Maybe this helps
function getValues(array, key) {
var result = [];
array.forEach(function (a) {
a[key] && result.push(a[key]);
});
return result;
}
var array = [{ "ghi": { "content": "abc" } }, { "def": { "imgURL": "test.png" } }, { "abc": { "key": "001" } }, { "ghi": { "content": "abc" } }, { "def": { "imgURL": "test.png" } }, { "abc": { "key": "001" } }];
document.write('<pre>' + JSON.stringify(getValues(array, 'ghi'), 0, 4) + '</pre>');

Categories

Resources