Flattening json such that one property is key and the other value - javascript

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)
});

Related

Getting total value of same id and display the final answer as an json array using angularjs

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)

Distinct json object in JavaScript

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>

Organize Array Items

I have the following JavaScript array:
var allItems = ['BBL_NO1', 'BBL_NO2', 'BBL_N03', 'BBL_NO4', 'AAL_NO1', 'AAL_NO2', 'MML_NO1', 'MML_NO2'];
Now I want to sort the array in this format, to put the values in a dropdown:
var sorted = { 'BBL': ['BBL_NO1', 'BBL_NO2', 'BBL_N03', 'BBL_NO4'],
'AAL': ['AAL_NO1', 'AAL_NO2'],
'MML': ['MML_NO1', 'MML_NO2']};
Does anyone know how I can do that?
You can do it using Array.prototype.reduce() function.
Example:
var allItems = ['BBL_NO1', 'BBL_NO2', 'BBL_N03', 'BBL_NO4', 'AAL_NO1', 'AAL_NO2', 'MML_NO1', 'MML_NO2'];
var sorted = allItems.reduce(function (acc, item) {
var mainPart = item.split('_')[0];
if (!acc.hasOwnProperty(mainPart)) {
acc[mainPart] = [];
}
acc[mainPart].push(item);
return acc;
}, {});
console.log(sorted);

JavaScript Reduce array on timestamp

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?

Create an array of Objects from JSON

I have a JSON file like below:
[
{"fields":{category_class":"CAT2",category_name":"A"},"pk":1 },
{"fields":{category_class":"CAT1",category_name":"B"},"pk":2 },
{"fields":{category_class":"CAT1",category_name":"C"},"pk":3 },
{"fields":{category_class":"CAT2",category_name":"D"},"pk":4 },
{"fields":{category_class":"CAT3",category_name":"E"},"pk":5 },
{"fields":{category_class":"CAT1",category_name":"E"},"pk":6 },
]
I want to create an array of objects from the above JSON which will have two properties. i) CategoryClass ii) CategoryNameList. For example:
this.CategoryClass = "CAT1"
this.CategoryNameList = ['B','C','E']
Basically i want to select all categories name whose category class is CAT1 and so forth for other categories class. I tried this:
var category = function(categoryClass, categoryNameList){
this.categoryClass = categoryClass;
this.categoryList = categoryNameList;
}
var categories = [];
categories.push(new category('CAT1',['B','C','E'])
Need help.
You can use a simple filter on the array. You have a few double quotes that will cause an error in you code. But to filter only with CAT1 you can use the filter method
var cat1 = arr.filter( value => value.fields.category_class === "CAT1");
I would suggest this ES6 function, which creates an object keyed by category classes, providing the object with category names for each:
function groupByClass(data) {
return data.reduce( (acc, { fields } ) => {
(acc[fields.category_class] = acc[fields.category_class] || {
categoryClass: fields.category_class,
categoryNameList: []
}).categoryNameList.push(fields.category_name);
return acc;
}, {} );
}
// Sample data
var data = [
{"fields":{"category_class":"CAT2","category_name":"A"},"pk":1 },
{"fields":{"category_class":"CAT1","category_name":"B"},"pk":2 },
{"fields":{"category_class":"CAT1","category_name":"C"},"pk":3 },
{"fields":{"category_class":"CAT2","category_name":"D"},"pk":4 },
{"fields":{"category_class":"CAT3","category_name":"E"},"pk":5 },
{"fields":{"category_class":"CAT1","category_name":"E"},"pk":6 },
];
// Convert
var result = groupByClass(data);
// Outut
console.log(result);
// Example look-up:
console.log(result['CAT1']);
Question : Basically i want to select all categories name whose category class is CAT1 and so forth for other categories class
Solution :
function Select_CatName(catclass,array){
var CatNameList=[]
$(array).each(function(){
if(this.fields.category_class==catclass)
CatNameList.push(this.fields.category_name)
})
return CatNameList;
}
This function return the Desired Category Name List, you need to pass desired catclass and array of the data , as in this case it's your JSON.
Input :
Above function calling :
Output :
Hope It helps.

Categories