I am trying to reduce this array based on the timestamp:
Var Data = [{"Group":"OPS","Date":"2017-04-18T00:00:00.000Z","Count":1},{"Group":"BOE","Date":"2017-04-19T00:00:00.000Z","Count":1},{"Group":"EDW","Date":"2017-04-21T00:00:00.000Z","Count":1},{"Group":"SUPPORT","Date":"2017-04-17T00:00:00.000Z","Count":1},{"Group":"EDWEXTRACTS","Date":"2017-04-17T00:00:00.000Z","Count":1},{"Group":"EDWEXTRACTS","Date":"2017-04-18T00:00:00.000Z","Count":1},{"Group":"SAFTT","Date":"2017-04-17T00:00:00.000Z","Count":1},{"Group":"SAFTT","Date":"2017-04-18T00:00:00.000Z","Count":2},{"Group":"SAFTT","Date":"2017-04-21T00:00:00.000Z","Count":1},{"Group":"OPS","Date":"2017-04-17T00:00:00.000Z","Count":1},{"Group":"VIEW","Date":"2017-04-17T00:00:00.000Z","Count":1},{"Group":"VIEW","Date":"2017-04-19T00:00:00.000Z","Count":3}]
I have tried to use the reduce method but seem to be doing something wrong.
var obj = {}
result.reduce(function(r, e) {
if (!obj[e.Date]) {
obj[e.Date] = {
Date: e.Date,
Assest: []
}
r.push(obj[e.Date])
}
obj[e.Date].Date.push(e.Group)
obj[e.Date].Date.push(e.Count)
return r
}, [])
console.log(JSON.stringify(result, 0, 4))
My desired outcome would be:
Var New_Data = [{"Date":"xx/xx/xx", "Assets":[{"group":"XXX"},{"Count":"X"}]},{"Date":"xx/xx/xx","Assets":[{"group":"XXX"},{"Count":"X"}]}]
Any Idea how I can achieve this, any help would be great.
Thanks =)
The code below is a working example. With this in hand you should be able to alter it to your exact specifications, if they differ from what I have implemented.
var Data = [
{"Group":"OPS","Date":"2017-04-18T00:00:00.000Z","Count":1},
{"Group":"BOE","Date":"2017-04-19T00:00:00.000Z","Count":1},
{"Group":"EDW","Date":"2017-04-21T00:00:00.000Z","Count":1},
{"Group":"SUPPORT","Date":"2017-04-17T00:00:00.000Z","Count":1},
{"Group":"EDWEXTRACTS","Date":"2017-04-17T00:00:00.000Z","Count":1},
{"Group":"EDWEXTRACTS","Date":"2017-04-18T00:00:00.000Z","Count":1},
{"Group":"SAFTT","Date":"2017-04-17T00:00:00.000Z","Count":1},
{"Group":"SAFTT","Date":"2017-04-18T00:00:00.000Z","Count":2},
{"Group":"SAFTT","Date":"2017-04-21T00:00:00.000Z","Count":1},
{"Group":"OPS","Date":"2017-04-17T00:00:00.000Z","Count":1},
{"Group":"VIEW","Date":"2017-04-17T00:00:00.000Z","Count":1},
{"Group":"VIEW","Date":"2017-04-19T00:00:00.000Z","Count":3}
];
Data = Data.reduce(function(r, e) {
var date = e.Date.match(/(\d+-\d+-\d+)/)[0].replace(/-/g, '/');
if (r[date] == undefined) {
r[date] = {Date: date, Assets: []};
}
r[date].Assets.push({Group: e.Group});
r[date].Assets.push({Count: e.Count});
return r
}, {});
console.log(Data);
You may need to convert the resulting object into an array:
new_data = [];
for(i in Data){
new_data.push(Data[i]);
}
What you need is something like this?
var result = dados.map(function (v) {
return {
Date: new Date(v["Date"]),
Assets: [
{Group: v['Group']},
{Count: v['Count']}
]
};
});
or Do you need to create a group?
Related
I have a Json array as follows
$scope.array = [{id:"1", tot:20},{id:"2", tot:30},{id:"1", tot:20},{id:"3", tot:50}];
I want to get the sum of tot belonging to same id and display the final answer as another Json array as follows
output:
[{id:"1", total:40},{id:"2", total:30},{id:"3", total:50}]
How can I achieve this using angularjs?
I'd solve this by using Array.reduce. Like this:
var array = [{id:"1", tot:20},{id:"2", tot:30},{id:"1", tot:20},{id:"3", tot:50}];
var res = array.reduce(function (agg, obj) {
var objForId = agg.filter(function (idObj) { return idObj.id === obj.id})[0]
if (objForId) {
objForId.total += obj.tot;
} else {
agg.push({
id: obj.id,
total: obj.tot
})
}
return agg;
}, [])
console.log(res)
I'm using spring boot and I generated a json object.
[
{"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"good","category":"AA"},
{"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"bad","category":"BB"},
{"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"poor","category":"CC"}
{"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"very bad","category":"AA"}
{"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"nice","category":"XX"}
{"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"okey","category":"YY"}
]
I have to distinct the date and get a new json object like following
[
{"date":"2017-11-20T17:12:01.340", "name":"abc", "feedback_1":"good", "feedback_2":"bad", "feedback_3":"poor", "category_1":"AA", "category_2":"BB", "category_3":"CC"},
{"date":"2017-12-15T16:53:02.042", "name":"xyz", "feedback_1":"very bad", "feedback_2":"nice", "feedback_3":"poor", "category_1":"AA", "category_2":"XX", "category_3":"YY"}
]
I try to get this format in Java or JavaScript. I tried my best using online resources but I failed since I'm new to JavaScript, how can I solve it? Thanks in advance.
You can use array#reduce to create an object and add counter to keep record of frequency of your JSON and using this counter add feedback and category. After that remove the counter from your result.
var data = [ {"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"good","category":"AA"}, {"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"bad","category":"BB"}, {"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"poor","category":"CC"}, {"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"very bad","category":"AA"}, {"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"nice","category":"XX"}, {"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"okey","category":"YY"} ];
var result = Object.values(data.reduce((r,o) => {
var key = o.data + "|" + o.name;
r[key] = r[key] || {date: o.date, name: o.name, count:1};
r[key] = Object.assign({}, r[key], {['feedback_'+r[key].count] : o.feedback, ['category_'+r[key].count]: o.category, count : r[key].count+1});
return r;
},{}));
result.forEach(o => delete o.count);
console.log(result);
take 2 array
1st array={"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"good","category":"AA"},
{"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"bad","category":"BB"},
{"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"poor","category":"CC"}
2nd={"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"very bad","category":"AA"}
{"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"nice","category":"XX"}
{"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"okey","category":"YY"}
and use array_unique to get unique values
You can try linq.js library:
var data = [{"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"good","category":"AA"}, {"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"bad","category":"BB"}, {"date":"2017-11-20T17:12:01.340","name":"abc","feedback":"poor","category":"CC"}, {"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"very bad","category":"AA"}, {"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"nice","category":"XX"}, {"date":"2017-12-15T16:53:02.042","name":"xyz","feedback":"okey","category":"YY"}];
var temp = Enumerable.From(data).GroupBy("$.date").Select("{date: $.Key(), name: $.First().name, feedback: Enumerable.From($).Select('$.feedback').ToArray(), category: Enumerable.From($).Select('$.category').ToArray() }").ToArray();
for (var item of temp) {
for (var prop of ['feedback', 'category']) {
for (var x of item[prop])
item[prop + '_' + (item[prop].indexOf(x) + 1)] = x
delete item[prop];
}
}
console.log(temp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>
I have data in following format..
var array = [{"name":"abc","boss":"def","sub":[{"schema":"a","data":1},{"schema":"b","data":0},{"schema":"c","data":0}]},
.
.
.
]
I wish to transform it to the following structure:
[{"name":"abc","boss":"def","a":1,"b":0,"c":0},
.
.
.
]
Based on the answer here.. I tried..
grouped = [];
array.forEach(function (a) {
if (!this[a.name]||!this[a.boss]) {
this[a.name] = { name: a.name, boss:a.boss };
grouped.push(this[a.name]);
}
this[a.name][a.sub.schema] = (this[a.name][a.sub.schema] || 0) + a.sub.data;
}, Object.create(null));
console.log(grouped);
The above gives undefined:NaN as the third property in the result objects..
Any help is sincerely appreciated.
Thanks
You probably want to reduce the sub object to properties of the item.
The following code maps the items in array to a new array, which contains the flattened items:
array = array.map(function(item) {
item = item.sub.reduce(function(x,y) { return x[y.schema] = y.data, x; }, item);
delete item.sub;
return item;
});
Try this simply.
var arr = [];
array.forEach(function(ele){
var obj = {};obj.name=ele.name;
obj.boss=ele.boss;
ele.sub.forEach(function(e){
obj[e.schema] = e.data
});
arr.push(obj)
});
Hello i want to filter json data like sql query without the help of plugins like alasql.js or linq.js or any plugins.
for example
{
"Managing PCL": [
{
"idItScreen": "1436",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListActiveTarif",
"busScreenName": "My Current Tarif"
},
{
"idItScreen": "1437",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListTermineTarif",
"busScreenName": "History Tarif"
}
]
}
for example i need to get data where idItScreen>1430 so that json data must be displayed the main challenge is to do without plugins so please reccomend me a good solution to do this without plugins
First turn your JSON into a Javascript object:
var obj = JSON.parse(myJSON);
Then do your filtering:
var matches = [];
var arr = obj['Managing PCL'];
for (var i = 0; i < arr.length; i++) {
if (arr[i].idItScreen > 1430) {
matches.push(arr[i]);
}
}
Or using jQuery.grep:
var matches = jQuery.grep(obj['Managing PCL'], function(n, i) {
return n.idItScreen > 1430;
});
Now matches contains the matching items.
If you want to get the JSON again, just use JSON.stringify:
var filteredJSON = JSON.stringify({'Managing PCL': matches});
You can also simply use .filter:
var matches = [];
var all = obj['Managing PCL'];
var filtered = all.filter(function(){
return $(this).idItScreen > 1430;
})
You don't need to use jQuery for this. You can use the filter() method of Array.prototype. See the working snippet below:
var obj = {
"Managing PCL": [{
"idItScreen": "1436",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListActiveTarif",
"busScreenName": "My Current Tarif"
}, {
"idItScreen": "1437",
"topicName": "Managing PCL",
"isFav": 0,
"cdeItScreen": "ListTermineTarif",
"busScreenName": "History Tarif"
}]
};
var filteredArray = obj['Managing PCL'].filter(function(item) {
return item.idItScreen > 1430;
});
obj['Managing PCL'] = filteredArray;
document.getElementById('result').innerHTML = JSON.stringify(obj);
<div id="result"></div>
You don't need jQuery for this. Use filter on the data instead.
function filterData(data, key, value) {
return data.filter(function (el) {
return el[key] > value;
});
}
// Note, `filter` operates on arrays, so you need to specify the
// array that contains the data
var result = filterData(data['Managing PCL'], 'idItScreen', '1430');
Also note that filter returns a new array containing the objects that it's found that match your criteria. You can access those objects in the usual way: result[0], for example.
DEMO
You could even expand this to create a function that returns data based on the operator too, not just greater-than, by using a look-up object:
var lookup = {
'>': function (data, value) { return data > value; },
'<': function (data, value) { return data < value; },
'===': function (data, value) { return data === value; }
}
function filterData(data, key, operator, value) {
return data.filter(function (el) {
return lookup[operator](el[key], value);
});
}
filterData(data['Managing PCL'], 'idItScreen', '>', '1430');
filterData(data['Managing PCL'], 'idItScreen', '===', '1430');
DEMO
I have a $scope object that has a date property. I am trying to split that date into dd, mm and yyyy so i can perform calculations based on the values.
JS:
$scope.expenses = [
{
amount: 100,
SpentOn: '19/04/2014'
},
{
amount: 350,
SpentOn: '01/09/2013'
}
];
$scope.MySplitDateFunction = function () {
var data = [];
var data = $scope.expenses.SpentOn.split('/');
data.day = SpentOn[0];
data.month = SpentOn[1];
data.year = SpentOn[2];
return data;
};
I am getting the following error: $scope.expenses.SpentOn is undefined
since in your program $scope.expenses has two objects and you have not specifies which is that
Try this out
$scope.MySplitDateFunction = function () {
var data = [];
var data = $scope.expenses[0].SpentOn.split('/');
return data;
};
$scope.expenses returns an array with 2 objects in it so you'll have to do something like
$scope.expenses[0].SpentOn // returns 19/04/2014
Or you can remove the [] to make it an object and not an array of objects
$scope.expenses seems to be an array with objects, you have to try
$scope.expenses[0].SpentOn