Group and summarize json data to new json object - javascript

I am using angularJS and have a JSON object from an API response which looks like the following:
var data = [
{"group": "red", "state": "running"},
{"group": "red", "state": "closed"},
{"group": "red", "state": "closed"},
{"group": "blue", "state": "running"},
{"group": "blue", "state": "running"}
];
I would like to parse this object inside a javascript function to get the following result:
var sumdata = [
{"group": "red", "running": 1, "closed": 2, "summary": 3},
{"group": "blue", "running": 2, "closed": 0, "summary": 2}
];
So, I have to group the first property called "group", then count how many objects in this group are in running state, closed state and also summarize the count of objects.
(Note:
I would not like to use extra javascript libraries like LINQ.js
)
Could yo help me please?
I tried the following, which is missing the group by and have no idea how to put that into this function:
var getSum = function (data) {
if (!data) {
$scope.data = [];
}
else {
for (var i = 0; i < data.length; i++) {
var group = data[i][0];
var status = data[i][1];
status = (status ? status.Name : "").toUpperCase();
var running = 0;
var closed = 0;
switch (status) {
case "RUNNING":
running++;
break;
case "CLOSED":
closed++;
break;
default:
break;
}
var summary = running + closed;
$scope.dataSum.push({ "group": group, "running": running, "closed": closed, "summary": summary});
}
}
};

This is a proposal with a temporary object and an Array#forEach loop in plain Javascript.
var data = [{ "group": "red", "state": "running" }, { "group": "red", "state": "closed" }, { "group": "red", "state": "closed" }, { "group": "blue", "state": "running" }, { "group": "blue", "state": "running" }],
grouped = function (array) {
var r = [];
array.forEach(function (a) {
if (!this[a.group]) {
this[a.group] = { group: a.group, running: 0, closed: 0, summary: 0 };
r.push(this[a.group]);
}
this[a.group][a.state]++;
this[a.group].summary++;
}, Object.create(null));
return r;
}(data);
document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');

With the LINQ power it will look something like that:
var data = [{
"group": "red",
"state": "running"
}, {
"group": "red",
"state": "closed"
}, {
"group": "red",
"state": "closed"
}, {
"group": "blue",
"state": "running"
}, {
"group": "blue",
"state": "running"
}];
var result = Enumerable.From(data).GroupBy('$.group', null, function(key, group) {
return {
group: key,
running: group.Where(function(value) {
return value.state == 'running'
}).Count(),
closed: group.Where(function(value) {
return value.state == 'closed'
}).Count(),
summary: group.Where(function(value) {
return value.state == 'running' || value.state == 'closed'
}).Count()
}
}).ToArray()
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>

The below snipped works for any number of fields in the data array. You only give the name of the field you want to group by. it is better than other examples in the way that it will work for any kind of data not only named like you suggested.
Hope it help.
(function(){
var data = [
{ "group": "red", "state": "running" },
{ "group": "red", "state": "closed" },
{ "group": "red", "state": "closed" },
{ "group": "blue", "state": "running" },
{ "group": "blue", "state": "running" },
{ "group": "blue", "state": "asd", "value":"33" },
{ "group": "blue", "state": "asd1", "value":"33" },
{ "group": "red", "state": "asd", "value":"33" }
],
grouped = function (array) {
var r = [];
var groupFieldName = "group";
array.forEach(function (a) {
var self = this;
if (!self[a[groupFieldName]]) {
var tempObj = {
group: a[groupFieldName]
};
self[a[groupFieldName]] = tempObj;
r.push(self[a[groupFieldName]]);
}
var keys = Object.keys(a);
keys.forEach(function(key){
if(key != groupFieldName){
if(self[a[groupFieldName]][a[key]] == undefined){
self[a[groupFieldName]][a[key]] = 1;
}else{
self[a[groupFieldName]][a[key]]++;
}
}
});
}, Object.create(null));
return r;
}(data);
console.log(JSON.stringify(grouped));
})()

Related

Comparing an array with another array plus adding a counter

So I'm reformatting my data and I noticed that my data isn't quite getting restructured the way I want it to. I noticed that my results come back as
[
{
"name": "sites",
"parent": null,
"count": 3
},
{
"name": "group1",
"parent": "sites",
"count": 3
},
{
"name": "bk",
"parent": "group1",
"count": 3
},
{
"name": "sitepages",
"parent": "bk",
"count": 1
},
{
"name": "home.aspx",
"parent": "sitepages",
"count": 1
}
]
It isn't grabbing my "not matches". I've spent so much time looking it over and I'm coming to a blank. It should be
[
{
"name": "sites",
"parent": null,
"count": 3
},
{
"name": "group1",
"parent": "sites",
"count": 3
},
{
"name": "bk",
"parent": "group1",
"count": 3
},
{
"name": "sitepages",
"parent": "bk",
"count": 1
},
{
"name": "home.aspx",
"parent": "sitepages",
"count": 1
},
{
"name": "tester",
"parent": "bk",
"count": 1
},
{
"name": "tester",
"parent": "home.aspx",
"count": 1
},
{
"name": "_layouts",
"parent": "bk",
"count": 1
},
{
"name": "15",
"parent": "_layouts",
"count": 1
},
{
"name": "upload.aspx",
"parent": "15",
"count": 1
},
]
I believe something is missing in my loop.
var testArr = [
{
Author: { Title: "Mitchell" },
BrowserType: "FireFox",
Created: "2017-04-25T16:39:40Z",
pathname: "sites/group1/bk/sitepages/home.aspx"
},
{
Author: { Title: "Pierre" },
BrowserType: "Opera",
Created: "2017-04-25T16:39:40Z",
pathname: "sites/group1/bk/tester/home.aspx"
},
{
Author: { Title: "Mizell" },
BrowserType: "IE",
Created: "2017-04-25T16:47:02Z",
pathname: "sites/group1/bk/_layouts/15/upload.aspx"
}
];
function reduceData(data) {
var root = null;
var newArr = null;
var itemContainer = [];
var masterArr = [];
var filteredArr = [];
data.forEach(function (props, idx) {
//check the last character of the pathname is "/" and removes it
if (props.pathname.charAt(props.pathname.length - 1) === "/") {
props.pathname = props.pathname.substring(0, props.pathname.length - 1);
}
//lowercase the pathname + split into strings
props.pathname = props.pathname.toLowerCase().split("/");
//format the pathname
var lastItem = "";
newArr = props.pathname.reduce(function (acc, props, index) {
if (acc.length === 0) {
acc.push({ name: props, parent: null, count: 1 });
lastItem = props;
} else {
acc.push({ name: props, parent: lastItem, count: 1 });
lastItem = props;
}
return acc;
}, []);
//The first iteration
if (idx === 0) {
itemContainer = newArr;
} else {
for (var i = 0; i < itemContainer.length; i++) {
// Loop for newArr
for (var j = 0; j < newArr.length; j++) {
//compare the element of each and every element from both of the arrays
//console.log(masterArr[i], newArr[j]);
if (
itemContainer[i].name === newArr[j].name &&
itemContainer[i].parent === newArr[j].parent
) {
//Match
masterArr[i] = {
name: itemContainer[i].name,
parent: itemContainer[i].parent,
count: itemContainer[i].count++
};
} else {
//Doesn't Match
masterArr[i] = {
name: itemContainer[i].name,
parent: itemContainer[i].parent,
count: itemContainer[i].count
};
}
}
}
}
});
console.log(masterArr)
}
reduceData(testArr)
ok.. I revamp your code a little..
delete the if else after the //The first iteration, and use this instead..
newArr.forEach((newEl) => {
const matchIdx = masterArr.findIndex((masterEl) => masterEl.name === newEl.name && masterEl.parent === newEl.parent);
if(matchIdx < 0){
masterArr.push(newEl);
}
else {
masterArr[matchIdx].count = masterArr[matchIdx].count + 1;
}
});

Automatic Random Test Data Generation of Documents for Seeding a MongoDB Database

I'm using JSON Generator https://next.json-generator.com to seed my MongoDB database. I'm finding trouble to generate a random set (from one to six) of colors out of the predefined group.
I've succeeded to generate all of the other property values but color. I need for the availableColors key to generate a random variable number of colors out of a predefined set of six: "blue", "brown", "green", "white", "yellow", "gray".
Here is the URL to the online generator where it is possible to real-time edit it: https://next.json-generator.com/E1g60a1pL
Here is the code:
[
{
'repeat(5, 10)': {
id: '{{objectId()}}',
name: '{{firstName()}}',
price: '{{floating(5, 4000, 2, "$0,0.00")}}',
availableColors: (colors) => {
var condition = '{{integer(1, 6)}}';
var color = [];
for (j = 0; j < condition+1; j++)
{color [j] = '{{random("blue", "brown", "green", "white", "yellow", "gray")}}';}
let unique_array = [];
for(let i = 0;i < color.length; i++) {
if(unique_array.indexOf(color[i]) == -1){
unique_array.push(color[i]);
}
}
return unique_array;
},
weight: '{{floating(1, 4000, 2, "0.00")}}',
inStock: '{{integer(0, 2000)}}'
}
}
]
Here is the result I get:
[
{
"id": "5ce82b1302c9777aac5fd681",
"name": "Blake",
"price": "$389.53",
"availableColors": [],
"weight": "3753.22",
"inStock": 449
},
{
"id": "5ce82b137ab9fe24eda22714",
"name": "Felicia",
"price": "$3,190.01",
"availableColors": [],
"weight": "3797.51",
"inStock": 1288
},
{
"id": "5ce82b135414eb7550aee368",
"name": "Bettye",
"price": "$227.41",
"availableColors": [],
"weight": "2182.52",
"inStock": 1288
},
{
"id": "5ce82b13f751e63a8506fbf2",
"name": "Mullen",
"price": "$3,306.81",
"availableColors": [],
"weight": "694.51",
"inStock": 821
},
{
"id": "5ce82b130544c7c08086a6bc",
"name": "Angelita",
"price": "$734.90",
"availableColors": [],
"weight": "3.44",
"inStock": 226
},
{
"id": "5ce82b130d9e2fc4c2a21e22",
"name": "Mcknight",
"price": "$3,582.76",
"availableColors": [],
"weight": "1183.82",
"inStock": 1917
},
{
"id": "5ce82b13fb509ee9c384a096",
"name": "Nannie",
"price": "$3,479.29",
"availableColors": [],
"weight": "754.85",
"inStock": 716
},
{
"id": "5ce82b13881cb29ec7a1772b",
"name": "Sutton",
"price": "$1,726.83",
"availableColors": [],
"weight": "1382.76",
"inStock": 1911
},
{
"id": "5ce82b1386ad13bffcf0923b",
"name": "Maria",
"price": "$1,679.58",
"availableColors": [],
"weight": "1106.28",
"inStock": 5
},
{
"id": "5ce82b13fccd87dbe6451971",
"name": "Noble",
"price": "$309.25",
"availableColors": [],
"weight": "1657.83",
"inStock": 235
}
]
I expect the "availableColors" of any document to be an array of one to six predefined colors. Any idea?
You needed to make a pure javascript loop with Math.random
I have updated the link:
https://next.json-generator.com/EJXO4xfaU
After having studied in deep the example provided in the home page of JSON Generator, I've found how to use its keywords to get the same result. By the way, following the schema of my document, I've added the way to randomly provide or not the value for all of the properties that are not required.
Here's the URL to the online editor: https://next.json-generator.com/4k8Wd87pU
Here is the code:
[{
'repeat(5, 10)': {
id: '{{objectId()}}',
name: '{{firstName()}}',
price(tags) {
const nRequired = tags.integer(0, 5);
if (nRequired) {
return tags.floating(5, 4000, 2, "$0,0.00");
}
},
availableColors(tags) {
const nRequired = tags.integer(0, 3);
if (!nRequired) return;
const Colors = ['blue', 'brown', 'green', 'white', 'yellow', 'gray'];
const nColors = tags.integer(0, Colors.length - 1); // generate a random integer from 0 to 5 will be used to select the total number of colors to add as values
const aColors = [];
for (j = 0; j <= nColors && !aColors[j]; j++) {
let sColor = tags.integer(0, Colors.length - 1); // generate a random integer from 0 to 5 that will be used as index to select a random color from the Colors array
if (aColors.indexOf(Colors[sColor]) == -1) {
aColors.push(Colors[sColor]);
}
}
return aColors;
},
weight(tags) {
const nRequired = tags.integer(0, 5);
if (nRequired) {
return tags.floating(1, 900, 2, "0.00");
}
},
inStock(tags) {
const nRequired = tags.integer(0, 2);
if (nRequired) {
return tags.integer(0, 2000);
}
}
}
}]

Convert polyhierarchy parent-child relationship to array (tree) - javascript or jquery

var data = [
{
"text": "BEHIND A COMMON MEAL: POLYPHENOLS IN FOOD ",
"id": "445",
"parentid": ""
},
{
"text": "2.2 First Course: Pasta With Tomato Sauce (Polyphenols in Wheat Bran and Tomato Byproducts)",
"id": "441",
"parentid": "445"
},
{
"text": "2.3 A Fresh Side Dish: Mixed Salad (Polyphenols From Fennel, Carrot)",
"id": "442",
"parentid": "445"
},
{
"text": "hello mr.sujai",
"id": "448",
"parentid": "445"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "445"
},
{
"text": "INTRODUCTION",
"id": "452",
"parentid": ""
},
{
"text": "1.2 The Tight Biochemical Connection Between Vegetables and Their Byproducts",
"id": "440",
"parentid": "452"
},
{
"text": "OTHER OFF-THE-MENU MISCELLANEOUS",
"id": "454",
"parentid": ""
},
{
"text": "SOMETHING TO DRINK",
"id": "456",
"parentid": ""
},
{
"text": "3.1 Orange Juice (Polyphenols From Orange Byproducts)",
"id": "443",
"parentid": "456"
},
{
"text": "3.2 Wine (Polyphenols From Grape and Wine Byproducts)",
"id": "444",
"parentid": "456"
},
{
"text": "understandings",
"id": "451",
"parentid": "456"
},
{
"text": "Polyphenols",
"id": "453",
"parentid": "451"
},
{
"text": "this is test",
"id": "458",
"parentid": "455"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "458"
},
{
"text": "hello",
"id": "447",
"parentid": "449"
},
{
"text": "hi",
"id": "459",
"parentid": "447"
},
{
"text": "polyhierarchy",
"id": "449",
"parentid": "459"
},
{
"text": "testing",
"id": "457",
"parentid": "458"
},
{
"text": "hi test",
"id": "450",
"parentid": "457"
},
{
"text": "speech",
"id": "446",
"parentid": "450"
}]
function jsonTree() {
// Keep a fast lookup dictionary
var dictionary = {};
for (var i = 0; i < data.length; i++) {
dictionary[data[i].id] = data[i];
}
for (var i = 0; i < data.length; i++) {
if (data[i].parentid == 449) {
var test = "";
}
if (data[i].parentid) {
var parent = dictionary[data[i].parentid];
arrData = parent;
if (parent) {
if (!parent.children) {
parent.children = [];
}
parent.children.push(data[i]);
// arrData.children.push(data[i]);
}
}
}
var arrData = [];
for (var i = 0; i < data.length; i++) {
if (data[i].parentid == 455) {
arrData.push(data[i]);
}
}
document.getElementById("test").innerHTML = JSON.stringify(arrData);
return false;
}
polyhierarchy term having different parent.
for (var i = 0; i < data.length; i++) {
dictionary[data[i].id] = data[i];
}
in this place same id is replaced. polyhierarchy having id is 449. when add to dictionary it is replaced.
Tree structure should be
1. BEHIND A COMMON MEAL: POLYPHENOLS IN FOOD
polyhierarchy
2. this is test
polyhierarchy
hello
hi
polyhierarchy
i need array with parent, child relationship.
There are a few mistakes.
You have duplicate id's for your polyhierarchie element. Because you're building a dictionary to lookup your ids, you're overwriting your child element the second/subsequent time you add it to your object.
{
"text": "polyhierarchy",
"id": "449", //<-- duplicate
"parentid": "459"
}
You have non existant parentIds.
{
"text": "SOMETHING TO DRINK",
"id": "456",
"parentid": "455" // <--- doesn't exist
}
The code got a little more complex than anticipated because of those two issues.
function mapData (data) {
//build a dictionary for: id -> [eles]
var map = data.reduce ((obj, ele) => {
obj[ele.id] = [ //let's make the lookup an array, to support multiple elements with the same id
...obj[ele.id] || [], //keep the existing elements or initialize it to an array
{...ele, children: []}
];
return obj
}, {});
return Object.keys (map).reduce ((arr, key) => {
let eles = map [key] || []; //process all elements
eles.forEach (ele => {
let parents = map [ele.parentid] || [];
let parent = parents [0];
if (!parent) {
parent = map [ele.parentid] = {children: [], root: true}
}
parent.children.push (ele);
if (parent.root && !~arr.indexOf (parent)) arr.push (parent);
});
return arr;
},[])
}
console.log (mapData (data))

Remove empty string in nested json object via AngularJS

I have an nested json object in which I need to remove empty values and create new json which should contain only data objects.
json file:
myData = [{
"id": 1,
"values": [{
"value": ""
}]
}, {
"id": 2,
"values": [{
"value": 213
}]
}, {
"id": 3,
"values": [{
"value": ""
}, {
"value": ""
}, {
"value": "abc"
}]
},{
"id": 4,
"values": [{
"value": ""
}]
},{
"id": 33,
"values": [{
"value": "d"
}]
}];
Output should be:
myNewData = [{
"id": 2,
"values": [{
"value": 213
}]
}, {
"id": 3,
"values": [{
"value": "abc"
}]
},{
"id": 33,
"values": [{
"value": "d"
}]
}];
So far I have created this:
angular.module('myapp',[])
.controller('test',function($scope){
$scope.myData = [{
"id": 1,
"values": [{
"value": ""
}]
}, {
"id": 2,
"values": [{
"value": 213
}]
}, {
"id": 3,
"values": [{
"value": ""
}, {
"value": ""
}, {
"value": "abc"
}]
},{
"id": 4,
"values": [{
"value": ""
}]
},{
"id": 33,
"values": [{
"value": "d"
}]
}];
})
.filter('filterData',function(){
return function(data) {
var dataToBePushed = [];
data.forEach(function(resultData){
if(resultData.values && resultData.values != "")
dataToBePushed.push(resultData);
});
return dataToBePushed;
}
});
Html:
<div ng-app="myapp">
<div ng-controller="test">
<div ng-repeat="data in myData | filterData">
Id:{{ data.id }}
</br>
Values: {{ data.values }}
</div>
</div>
</div>
I am not able to access and remove value inside values object. Right now i am simply showing the data using ng-repeat but i need to create a new json file for that.
You work with the array in your AngularJS Controller doing Array.prototype.map() and Array.prototype.filter(). Map all objects doing a filter to exclude the items with empty values item.values.value, and than a filter to get the array elements that have values with value:
var myData = [{"id": 1,"values": [{ "value": ""}]}, {"id": 2,"values": [{"value": 213}]}, {"id": 3,"values": [{"value": ""}, {"value": ""}, {"value": "abc"}]}, {"id": 4,"values": [{"value": ""}]}, {"id": 33,"values": [{"value": "d"}]}],
myDataFiltered = myData
.map(function (item) {
item.values = item.values.filter(function (itemValue) {
return itemValue.value;
});
return item;
})
.filter(function (item) {
return item.values.length;
});
console.log(myDataFiltered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6:
myDataFiltered = myData
.map(item => {
item.values = item.values.filter(itemValue => itemValue.value);
return item;
})
.filter(item => item.values.length);
Here you go with a multiple for-loop.
myData = [{
"id": 1,
"values": [{
"value": ""
}]
}, {
"id": 2,
"values": [{
"value": 213
}]
}, {
"id": 3,
"values": [{
"value": ""
}, {
"value": ""
}, {
"value": "abc"
}]
},{
"id": 4,
"values": [{
"value": ""
}]
},{
"id": 33,
"values": [{
"value": "d"
}]
}];
function clone(obj){ return JSON.parse(JSON.stringify(obj));}
var result = [];
for(var i = 0; i < myData.length; i++){
var current = clone(myData[i]);
for(var j = 0; j < current.values.length; j++){
if(current.values[j].value == null || current.values[j].value == ""){
current.values.splice(j, 1);
j--;
}
}
if(current.values.length > 0) result.push(current);
}
console.log(myData);
console.log(result);
If you want to delete them completely, you can iterate over the array like this;
angular.forEach($scope.myData, function(data){
for(var i=0; i < data.values.length; i++){
if(data.values[i] !== ""){
break;
}
delete data;
}
});
The if statement checks all values in the array, and breaks if it's not equal to "", otherwise if all values are = "" it deletes the object.
Hope it helps!
Here's a recursive function to do the job.
This will only work if myData is an array and the value inside it or its children is a collection of object.
var myData = [{"id": 1, "values": [{"value": ""}] }, {"id": 2, "values": [{"value": 213 }] }, {"id": 3, "values": [{"value": ""}, {"value": ""}, {"value": "abc"}] },{"id": 4, "values": [{"value": ""}] },{"id": 6, "values": ""},{"id": 33, "values": [{"value": "d"}] }];
function removeEmptyValues (arr) {
var res = false;
/* Iterate the array */
for (var i = 0; i < arr.length; i++) {
/* Get the object reference in the array */
var obj = arr[i];
/* Iterate the object based on its key */
for (var key in obj) {
/* Ensure the object has the key or in the prototype chain */
if (obj.hasOwnProperty(key)) {
/* So, the object has the key. And we want to check if the object property has a value or not */
if (!obj[key]) {
/*
If it has no value (null, undefined, or empty string) in the property, then remove the whole object,
And reduce `i` by 1, to do the re-checking
*/
arr.splice(i--, 1);
/* Amd set whether the removal occurance by setting it to res (result), which we will use for the next recursive function */
res = true;
/* And get out from the loop */
break;
}
/* So, the object has a value. Let's check whether it's an array or not */
if (Array.isArray(obj[key])) {
/* Kay.. it's an array. Let's see if it has anything in it */
if (!obj[key].length) {
/* There's nothing in it !! Remove the whole object again */
arr.splice(i--, 1);
/* Amd set whether the removal occurance by setting it to res (result), which we will use for the next recursive function */
res = true;
/* Yes.. gets out of the loop */
break;
}
/*
Now this is where `res` is being used.
If there's something removed, we want to re-do the checking of the whole object
*/
if ( removeEmptyValues(obj[key]) ) {
/* Something has been removed, re-do the checking */
i--;
}
}
}
}
}
return res;
}
removeEmptyValues (myData);
Try this:
var myData = [{"id": 1,"values": [{ "value": ""}]}, {"id": 2,"values": [{"value": 213}]}, {"id": 3,"values": [{"value": ""}, {"value": ""}, {"value": "abc"}]}, {"id": 4,"values": [{"value": ""}]}, {"id": 33,"values": [{"value": "d"}]}]
let result=[],p=[];
myData.filter(el => {
p=[];
el.values.filter(k => {k.value != '' ? p.push({value : k.value}) : null});
if(p.length) result.push({id : el.id, values : p})
})
console.log('result', result);
You are going to right way but need some more operation like this :
angular.module('myapp',[])
.controller('test',function($scope){
$scope.myData = [{
"id": 1,
"values": [{
"value": ""
}]
}, {
"id": 2,
"values": [{
"value": 213
}]
}, {
"id": 3,
"values": [{
"value": ""
}, {
"value": ""
}, {
"value": "abc"
}]
},{
"id": 4,
"values": [{
"value": ""
}]
},{
"id": 33,
"values": [{
"value": "d"
}]
}];
})
.filter('filterData',function($filter){
return function(data) {
var dataToBePushed = [];
data.forEach(function(resultData){
var newValues=resultData;
var hasData=$filter('filter')(resultData.values,{value:'!'},true);
if(resultData.values && resultData.values.length>0 && hasData.length>0){
newValues.values=hasData;
dataToBePushed.push(newValues);
}
});
debugger;
return dataToBePushed;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="test">
<div ng-repeat="data in myData | filterData:''">
Id:{{ data.id }}
</br>
Values: {{ data.values }}
</div>
</div>
</div>

data transformation from one form of array to another

I have doubt about data structure transformation from one form of array to another.
My input data is of the form,
var testVar=[
{
"count": 1,
"term": "Company",
"Company": [
{
"Tata": [
{
"count": 1,
"term": "Tatagroup"
}
],
"sector": "Automotive",
"type": "Car"
},
]
},
{
"count": 2,
"term": "Country",
"Country": [
{
"France": [
{
"count": 1,
"term": "France"
}
],
"region": "Europe",
"Player": "Zidane",
"term": "France",
"code": "FRA"
},
{
"region": "Europe",
"Player": "Federer",
"term": "Switzerland",
"Switzerland": [
{
"count": 1,
"term": "Switzerland"
}
],
"code": "SWI"
}
]
}];
and I am trying to transform it to the form,
[ "Tata" : [{"sector" : "automotive"}, "type" : "car"], "France": [{"region" : "Europe}, {"Player" : "Zidane"} , {"code" : "FRA"}], "switzerland" : [{"region" : "Europe}, {"Player" : "Federer"} , {"code" : "SWI"}]];
The code I came up with looks like http://jsfiddle.net/X2apw/2/, bt its nt accurate..
var testvar = [...];
var result = {};
for (var i=0; i<testvar.length; i++) {
var arr = testvar[i][testvar[i].term];
for (var j=0; j<arr.length; j++) {
var resarr = [];
for (var k in arr[j]) {
if (typeof arr[j][k] == "string") {
var obj = {};
obj[k] = arr[j][k];
resarr.push(obj);
} else {
result[k] = resarr;
}
}
}
}
(Demo at jsfiddle.net)
However, I strongly recommend to use just one object instead of an array of one-property-objects in your result format. Change the inner loop body to:
var resobj = {};
for (var k in arr[j]) {
if (typeof arr[j][k] == "string") {
resobj[k] = arr[j][k];
} else {
result[k] = resobj;
}
}
(Demo)

Categories