Javascript Json formatting - javascript

I've a json like below
[
{
"name": "Item",
"attribute_list": [
{
"name": "Attribute 1",
"value_list": [
{
"value": "1"
},
{
"value": "2"
}
]
},
{
"name": "Attribute 2",
"value_list": [
{
"value": "10"
},
{
"value": "60"
},
{
"value": "80"
}
]
}
]
}
]
I want to change format like below
[
{
"Item": [{
"Attribute 1": "1", "Attribute 2": "10"
}]
}
]
What I've done already:
results.map(items => {
data[items.name.toLowerCase().replace(/ /g, '_')] = items.attribute_list?
items.attribute_list.reduce(
(obj, item) => Object.assign(obj, { [item.name.toLowerCase().replace(/ /g, '_')]: item.value_list?item.value_list[0].value:null }), {})
:null
})
Thanks in advance

If I understood everything correctly, you can do it like this:
const input = [
{
"name": "Item",
"attribute_list": [
{
"name": "Attribute 1",
"value_list": [
{
"value": "1"
},
{
"value": "2"
}
]
},
{
"name": "Attribute 2",
"value_list": [
{
"value": "10"
},
{
"value": "60"
},
{
"value": "80"
}
]
}
]
}
];
const result = input.map((entry) => {
return {
[entry.name]: [entry.attribute_list.reduce((res, curr) => {
res[curr.name] = curr.value_list[0].value;
return res;
}, {})]
};
});
console.log(result);

Related

How do I destructure this deep nested json objects and map it in JS

I have a nested array like below. There are about 100 de objects in the array. The de objects also have deg[0] array but most likely I will only have the first index. Now the trick is that the de are subset of deg. Which means each deg can have say 10 de. How can I retrieve the deg and there associated de and map it into a new array like:
newArray = [
deg1: [
{de1},
{de2}
],
deg2: [
{de1},
{de2}
]
]
Here is my nested array. I posted four but the list is over a 100.
{
"name": "Report",
"id": "2YYUEZ6I1r9",
"dse1": [
{
"de1": {
"name": "Number",
"id": "HjMOngg3kuy",
"de1-av": [
{
"value": "FHaQMPv9zc7",
"attribute": {
"id": "uwVkIP7PZDt"
}
},
{
"value": "something",
"attribute": {
"id": "FHaQMPv9zc7"
}
}
],
"deg1": [
{
"name": "TB",
"id": "2XJB1JO9qX8"
}
]
}
},
{
"de2": {
"name": "Number of",
"id": "a3dtGETTawy",
"de2-av": [
{
"value": "FHaQMPv9zc7",
"attribute": {
"id": "uwVkIP7PZDt"
}
},
{
"value": "something",
"attribute": {
"id": "FHaQMPv9zc7"
}
}
],
"deg1": [
{
"name": "Secondary",
"id": "w99RWzXHgtw"
}
]
}
},
{
"de1": {
"name": "Number of",
"id": "a3dtGETTawy",
"de1av": [
{
"value": "FHaQMPv9zc7",
"attribute": {
"id": "uwVkIP7PZDt"
}
},
{
"value": "something",
"attribute": {
"id": "FHaQMPv9zc7"
}
}
],
"deg2": [
{
"name": "Secondary",
"id": "w99RWzXHgtw"
}
]
}
},
{
"de2": {
"name": "Number of",
"id": "a3dtGETTawy",
"de2av": [
{
"value": "FHaQMPv9zc7",
"attribute": {
"id": "uwVkIP7PZDt"
}
},
{
"value": "something",
"attribute": {
"id": "FHaQMPv9zc7"
}
}
],
"deg2": [
{
"name": "Tertiary",
"id": "w99RWzXHgtw"
}
]
}
}
]
}
Group array of objects by property (this time a property to be matched by a reg exp) using Array.reduce.
Update: Ignoring missing keys.
var input={name:"Report",id:"2YYUEZ6I1r9",dse1:[{de1:{name:"Number",id:"HjMOngg3kuy","de1-av":[{value:"FHaQMPv9zc7",attribute:{id:"uwVkIP7PZDt"}},{value:"something",attribute:{id:"FHaQMPv9zc7"}}],deg1:[{name:"TB",id:"2XJB1JO9qX8"}]}},{de2:{name:"Number of",id:"a3dtGETTawy","de2-av":[{value:"FHaQMPv9zc7",attribute:{id:"uwVkIP7PZDt"}},{value:"something",attribute:{id:"FHaQMPv9zc7"}}],deg1:[{name:"Secondary",id:"w99RWzXHgtw"}]}},{de1:{name:"Number of",id:"a3dtGETTawy",de1av:[{value:"FHaQMPv9zc7",attribute:{id:"uwVkIP7PZDt"}},{value:"something",attribute:{id:"FHaQMPv9zc7"}}],deg2:[{name:"Secondary",id:"w99RWzXHgtw"}]}},{de2:{name:"Number of",id:"a3dtGETTawy",de2av:[{value:"FHaQMPv9zc7",attribute:{id:"uwVkIP7PZDt"}},{value:"something",attribute:{id:"FHaQMPv9zc7"}}],deg2:[{name:"Tertiary",id:"w99RWzXHgtw"}]}}]}
var reg = new RegExp("^de[0-9]+$");
var reg2 = new RegExp("^deg[0-9]+$");
let obj = input['dse1'].reduce(function(agg, item) {
// do your group by logic below this line
var key = Object.keys(item).find(function(key) {
return key.match(reg) ? key : null;
})
if (key) {
var key2 = Object.keys(item[key]).find(function(key) {
return key.match(reg2) ? key : null;
})
agg[key] = agg[key] || [];
if (key2) {
var to_push = {}
to_push[key2] = item[key][key2]
agg[key].push(to_push)
}
}
// do your group by logic above this line
return agg
}, {});
console.log(obj)
.as-console-wrapper {
max-height: 100% !important;
}

get size of value in a map javascript

I have below array object of key of Id and List of value pair. I want to get for each key what is the length of the value like
[
{
"key": "a5a5E0000003uzTQAQ",
"value": 1
},
{
"key": "a5a5E0000003uzYQAQ",
"value": 2
}
]
I am trying below code , but it is giving me undefined in the length of the value.
var message = [
{
"key": "a5a5E0000003uzTQAQ",
"value": [
{
"Name": "Features1"
}
]
},
{
"key": "a5a5E0000003uzYQAQ",
"value": [
{
"Name": "AEO Analysis - Engagement"
},
{
"Name": "AEO Analysis - Engagement 1",
}
]
}
]
let noOfFields = []
for (let key in message) {
if (message.hasOwnProperty(key)) {
noOfFields.push({key: key, value: message[key].length });
}
}
console.log(noOfFields)
You can use array.map
const message = [
{
"key": "a5a5E0000003uzTQAQ",
"value": [
{
"Name": "Features1"
}
]
},
{
"key": "a5a5E0000003uzYQAQ",
"value": [
{
"Name": "AEO Analysis - Engagement"
},
{
"Name": "AEO Analysis - Engagement 1",
}
]
}
]
const noOfFields = message.map((obj) => {
return {
key: obj.key,
value: obj.value.length
}
})
console.log(noOfFields)
Result:
[
{ key: 'a5a5E0000003uzTQAQ', value: 1 },
{ key: 'a5a5E0000003uzYQAQ', value: 2 }
]
If you want the length you just need this:
var message = [
{
"key": "a5a5E0000003uzTQAQ",
"value": [
{
"Name": "Features1"
}
]
},
{
"key": "a5a5E0000003uzYQAQ",
"value": [
{
"Name": "AEO Analysis - Engagement"
},
{
"Name": "AEO Analysis - Engagement 1",
}
]
}
]
let noOfFields = []
for (let key in message) {
if (message.hasOwnProperty(key)) {
noOfFields.push({key: key, value: message[key].value.length });
}
}
console.log(noOfFields)
It's a little misleading to call the length of the value 'value' though.

Nested Object based on .(dot)

I have Object Like this
var RecuiterInfo = {}
RecruiterInfo.Quote: "1"
RecruiterInfo.CompanyName: "Imperial Innovations",
RecruiterInfo.OrganizationSize: "2",
RecruiterInfo.Person.CitizanZenship: null,
RecruiterInfo.Person.DOB: "Farkhonda#hotmail.com",
RecruiterInfo.Person.Email: "Farkhonda",
RecruiterInfo.Person.FirstName: "FaiZi",
RecruiterInfo.Person.Gender: "4456565656"
RecruiterInfo.Person.LastName: "4456565656",
RecruiterInfo.Person.PhoneNo: "4456565656",
RecruiterInfo.Person.UserId.UserName: "MTIzNDU2",
RecruiterInfo.Person.UserId.Password: null
I want to convert this object to
this specific format Like
{
"QueryObjectID":"RecruiterInfo",
"Values": [
{
"AppFieldID": "Person",
"Value": [
{
"AppFieldID": "CitizanZenship",
"Value": "1"
},
{
"AppFieldID": "DOB",
"Value": "01/01/2019"
},
{
"AppFieldID": "Email",
"Value": "test1#test.com"
},
{
"AppFieldID": "FirstName",
"Value": "test"
},
{
"AppFieldID": "Gender",
"Value": "1"
},
{
"AppFieldID": "LastName",
"Value": "test last"
},
{
"AppFieldID": "PhoneNo",
"Value": "7897897895"
},
{
"AppFieldID": "UserId",
"Value": [
{
"AppFieldID": "UserName",
"Value": "test1#test.com"
},
{
"AppFieldID": "Password",
"Value": "123456"
}
]
}
]
},
{
"AppFieldID": "Quote",
"Value": "Hi Im test"
},
{
"AppFieldID": "CompanyName",
"Value": "Terst"
}
]
}
but it should be a generic/dynamic(I don't want any static stuff here, because in feature there will be a multiple dot/ or nested objects)
I think loop will be based on .(dot),and it will be nested not sure
can any one help me for this json convert
Thanks in advance
You can do it recursively.
const convert = (obj) => {
if (obj === null) return null
if (typeof obj !== 'object') return obj
return Object.entries(obj)
.reduce((acc, [key, value]) => acc.concat({
AppFieldId: key,
Value: convert(value), // Recursive call
}), [])
}
console.log(JSON.stringify(convert(RecruiterInfo), null, 2))
It's not exactly like you want, but you'd need static stuff for that first bit.
[
{
"AppFieldId": "Quote",
"Value": "1"
},
{
"AppFieldId": "CompanyName",
"Value": "Imperial Innovations"
},
{
"AppFieldId": "OrganizationSize",
"Value": "2"
},
{
"AppFieldId": "Person",
"Value": [
{
"AppFieldId": "CitizanZenship",
"Value": null
},
{
"AppFieldId": "DOB",
"Value": "Farkhonda#hotmail.com"
},
{
"AppFieldId": "Email",
"Value": "Farkhonda"
},
{
"AppFieldId": "FirstName",
"Value": "FaiZi"
},
{
"AppFieldId": "Gender",
"Value": "4456565656"
},
{
"AppFieldId": "LastName",
"Value": "4456565656"
},
{
"AppFieldId": "PhoneNo",
"Value": "4456565656"
},
{
"AppFieldId": "UserId",
"Value": [
{
"AppFieldId": "UserName",
"Value": "MTIzNDU2"
},
{
"AppFieldId": "Password",
"Value": null
}
]
}
]
}
]
You could take an iterative approach.
var data = { 'RecruiterInfo.Quote': "1", 'RecruiterInfo.CompanyName': "Imperial Innovations", 'RecruiterInfo.OrganizationSize': "2", 'RecruiterInfo.Person.CitizanZenship': null, 'RecruiterInfo.Person.DOB': "Farkhonda#hotmail.com", 'RecruiterInfo.Person.Email': "Farkhonda", 'RecruiterInfo.Person.FirstName': "FaiZi", 'RecruiterInfo.Person.Gender': "4456565656", 'RecruiterInfo.Person.LastName': "4456565656", 'RecruiterInfo.Person.PhoneNo': "4456565656", 'RecruiterInfo.Person.UserId.UserName': "MTIzNDU2", 'RecruiterInfo.Person.UserId.Password': null },
result = Object.entries(data).reduce((r, [s, v]) => {
var path = s.split('.'),
last = path.pop();
path
.reduce((o, k, i) => {
var temp = o.find(q => q[i ? 'AppFieldID' : 'QueryObjectID'] === k);
if (!temp) o.push(temp = i ? { AppFieldID: k, Value: [] } : { QueryObjectID: k, Values: [] });
return temp[i ? 'Value' : 'Values'];
}, r)
.push({ AppFieldID: last, Value: v });
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to group similar sub-items of JSON

I want to group similar sub-item of my Json into one and then merge all their sub-item under that created item.
this is my json file:
{
"car": [
{
"name": "benz",
"details": [
{
"name": "C1",
"year": [
{
"name": "1850",
"errs": [
{
"user": "model-A",
"text": "error text on model-H"
},
{
"user": "model-C",
"text": "error text on model-C"
}
]
},
{
"name": "1820",
"errs": [
{
"user": "model-C",
"text": "error text on model-C"
}
]
}
]
}
]
},
{
"name": "vw",
"details": [
{
"name": "A1",
"year": [
{
"name": "1860",
"errs": []
},
{
"name": "1870",
"errs": [
{
"user": "model-A",
"text": "error text on model-H"
}
]
}
]
},
{
"name": "A2",
"year": [
{
"name": "1910",
"errs": []
},
{
"name": "1950",
"errs": [
{
"user": "model-A",
"text": "error text on model-H"
}
]
}
]
}
]
}
]
}
my tree structure is based on label and children, so my parent item is label and sub tree is children.
and this is my ts file:
ngOnInit():void {
this.http.get('.car.json').subscribe((data) => {
data.car.forEach((carItem) => {
carItem.details.forEach((detail) => {
const errorsTree = {};
detail.year.forEach((year) => {
year.errs.forEach((err) => {
let userNode;
let carNode;
let detailNode;
if (errorsTree[err.userAgent]) {
userNode = errorsTree[err.userAgent];
} else {
userNode = {name: err.userAgent, cars: {}};
errorsTree[err.userAgent] = userNode;
}
const components = userNode.cars;
if (components[carItem.name]) {
carNode = cars[carItem.name];
} else {
carNode = {name: carItem.name, details: {}};
components[carItem.name] = carNode;
}
const detailsItems = carNode.details;
if (detailsItems[detail.name]) {
detailNode = detailsItems[detail.name];
} else {
detailNode = {name: detail.name, tests: {}};
detailsItems[detail.name] = detailNode;
}
detailNode.tests[test.name] = test;
this.TreeModel.push({
label: userNode.name,
children: _.values(userNode.cars).map((car) => {
return {
label: car.name,
children: _.values(car.details).map((deta) => {
return {
label: deta.name,
children: _.values(deta.tests).map((testItem) => {
return {
label: testItem.name,
err: err.text
};
})
};
})
};
})
});
});
});
});
});
});
}
after running the code the tree will be like this:
model-A
benz
C1
model-C
benz
C1
model-C
benz
C1
model-A
vw
A1
model-A
vw
A2
but it is not correct, the result should be like following:
[
{
label: 'model-A',
children: [
{
label: 'benz',
children: [
{
label: 'C1'
}
]
},
{
label: 'vw',
children: [
{
label: 'A1'
},
{
label: 'A2'
}
]
}
]
},
{
label: 'model-C',
children: [
{
label: 'benz',
children: [
{
label: 'C1'
}
]
}
]
}
]
do you have i idea how to group this Json like the above structure with Angular 5
thanks.
You can use something like this -
var processedJSON = {};
const data = {
"car": [{
"name": "benz",
"details": [{
"name": "C1",
"year": [{
"name": "1850",
"errs": [{
"user": "model-A",
"text": "error text on model-H"
},
{
"user": "model-C",
"text": "error text on model-C"
}
]
},
{
"name": "1820",
"errs": [{
"user": "model-C",
"text": "error text on model-C"
}]
}
]
}]
},
{
"name": "vw",
"details": [{
"name": "A1",
"year": [{
"name": "1860",
"errs": []
},
{
"name": "1870",
"errs": [{
"user": "model-A",
"text": "error text on model-H"
}]
}
]
},
{
"name": "A2",
"year": [{
"name": "1910",
"errs": []
},
{
"name": "1950",
"errs": [{
"user": "model-A",
"text": "error text on model-H"
}]
}
]
}
]
}
]
};
data.car.forEach(function(car, i) {
car.details.forEach(function(detail, j) {
detail.year.forEach(function(year, k) {
year.errs.forEach(function(element, l) {
if (!processedJSON[element.user]) {
processedJSON[element.user] = {};
}
if (!processedJSON[element.user][car.name]) {
processedJSON[element.user][car.name] = [];
}
if (processedJSON[element.user][car.name].indexOf(detail.name) == -1) {
processedJSON[element.user][car.name].push(detail.name);
}
});
});
});
});
console.log(processedJSON);
You can structure your data using array#reduce with multiple array#forEach, then from this result, use array#map with Object.keys() to get the final format.
const data = { "car": [ { "name": "benz", "details": [ { "name": "C1", "year": [ { "name": "1850", "errs": [ { "user": "model-A", "text": "error text on model-H" }, { "user": "model-C", "text": "error text on model-C" } ] }, { "name": "1820", "errs": [ { "user": "model-C","text": "error text on model-C" } ] } ] } ] }, { "name": "vw", "details": [ { "name": "A1", "year": [ { "name": "1860", "errs": [] }, { "name": "1870", "errs": [ { "user": "model-A", "text": "error text on model-H" } ] } ] }, { "name": "A2", "year": [{ "name": "1910", "errs": [] }, { "name": "1950", "errs": [ { "user": "model-A", "text": "error text on model-H" } ] } ] } ] } ] },
result = data.car.reduce((r, {name, details}) => {
details.forEach(o1 => {
o1.year.forEach(o2 => {
o2.errs.forEach(({user, text}) => {
r[user] = r[user] || {};
r[user][name] = r[user][name] || [];
if(!r[user][name].includes(o1.name))
r[user][name].push(o1.name);
});
});
});
return r;
},{});
const output = Object.keys(result).map(k => ({label : k, children : Object.keys(result[k]).map(key => ({label: key, children : result[k][key].map(([label]) => ({label}) ) }) ) }) );
console.log(output);

transforming json using recursive function

I'm trying to transform this JSON into array so that I can simply list them as key-value pairs in html. The JSON has nested properties which I want to retain but I want to stringify only those objects that contain "units" and "value". All others should be listed as children items. Please help figure what I'm doing wrong.
Here's the json input:
{
"clusterName": "ml6.engrlab.com-cluster",
"statusProperties": {
"loadProperties": {
"loadDetail": {
"restoreWriteLoad": {
"value": 0,
"units": "sec/sec"
},
},
"totalLoad": {
"value": 0.0825921967625618,
"units": "sec/sec"
}
},
"secure": {
"value": false,
"units": "bool"
},
"statusDetail": {
"licenseKeyOption": [
{
"value": "conversion",
"units": "enum"
},
{
"value": "failover",
"units": "enum"
}
],
"connectPort": 7999,
"softwareVersion": {
"value": 9000100,
"units": "quantity"
}
},
"rateProperties": {
"rateDetail": {
"largeReadRate": {
"value": 0,
"units": "MB/sec"
}
},
"totalRate": {
"value": 67.2446365356445,
"units": "MB/sec"
}
},
"online": {
"value": true,
"units": "bool"
},
"cacheProperties": {
"cacheDetail": {
"tripleCachePartitions": {
"tripleCachePartition": [
{
"partitionSize": 768,
"partitionBusy": 0,
"partitionUsed": 0,
"partitionFree": 100
}
]
}
}
}
}
}
my code
function isNested(obj) {
if(!obj) return false;
let propArry = Object.keys(obj)
for(let i=0; i<propArry.length; i++){
if(obj[propArry[0]].constructor.name === 'Object') return true
}
return false;
}
function getKeyValueAsChildren(obj) {
let vals = [];
for(let key in obj) {
if(obj.hasOwnProperty(key)){
vals.push({key:key, value: obj[key]})
}
}
return vals
}
function valueAsString(obj) {
if(typeof obj !== 'object') return obj;
return `${obj['value']} ${obj['units']}`
}
function getChildren(key, obj) {
if(Object.keys(obj).sort().toString() === "units,value"){
return {key: key, value: valueAsString(obj)}
} else {
return {key: key, children: getKeyValueAsChildren(obj) }
}
}
function getValues(properties, values = []) {
for(let key in properties) {
if(properties.hasOwnProperty(key)) {
let value = properties[key]
if(typeof value !== 'object') {
values.push({key: key, value: value})
} else if(Array.isArray(value)){
let children = []
value.map(v => {
children.push(getChildren(key, v))
})
values.push({key: `${key}List`, children: children})
}
else if(value.constructor.name === 'Object' && isNested(value)){
// I THINK THE MAIN PROBLEM IS HERE
let keys = Object.keys(value)
let children = [];
keys.forEach(key => {
children.push({key: key, children: getValues(value[key])})
})
values.push({key: key, children: children})
}
else {
values.push(getChildren(key, value))
}
}
}
return values
}
getValues(hostProperties)
this returns
[
{
"key": "clusterName",
"value": "ml6.engrlab.com-cluster"
},
{
"key": "statusProperties",
"children": [
{
"key": "loadProperties",
"children": [
{
"key": "loadDetail",
"children": [
{
"key": "restoreWriteLoad",
"children": [
{
"key": "value",
"value": 0
},
{
"key": "units",
"value": "sec/sec"
}
]
}
]
},
{
"key": "totalLoad",
"value": "0.0825921967625618 sec/sec"
}
]
},
{
"key": "secure",
"children": [
{
"key": "value",
"value": false
},
{
"key": "units",
"value": "bool"
}
]
},
{
"key": "statusDetail",
"children": [
{
"key": "licenseKeyOptionList",
"children": [
{
"key": "licenseKeyOption",
"value": "conversion enum"
},
{
"key": "licenseKeyOption",
"value": "failover enum"
}
]
},
{
"key": "connectPort",
"value": 7999
},
]
},
{
"key": "rateProperties",
"children": [
{
"key": "rateDetail",
"children": [
{
"key": "largeReadRate",
"children": [
{
"key": "value",
"value": 0
},
{
"key": "units",
"value": "MB/sec"
}
]
}
]
},
{
"key": "totalRate",
"value": "67.2446365356445 MB/sec"
}
]
},
{
"key": "online",
"children": [
{
"key": "value",
"value": true
},
{
"key": "units",
"value": "bool"
}
]
},
{
"key": "cacheProperties",
"children": [
{
"key": "cacheDetail",
"children": [
{
"key": "tripleCachePartitions",
"children": [
{
"key": "tripleCachePartitionList",
"children": [
{
"key": "tripleCachePartition",
"children": [
{
"key": "partitionSize",
"value": 768
},
{
"key": "partitionBusy",
"value": 0
},
{
"key": "partitionUsed",
"value": 0
},
{
"key": "partitionFree",
"value": 100
}
]
}
]
}
]
}
]
}
]
}
]
}
]
but I need this
[
{
"key": "clusterName",
"value": "ml6.engrlab.com-cluster"
},
{
"key": "statusProperties",
"children": [
{
"key": "loadProperties",
"children": [
{
"key": "loadDetail",
"children": [
{
"key": "restoreWriteLoad",
"value": "0 sec/sec"
}
]
},
{
"key": "totalLoad",
"value": "0.0825921967625618 sec/sec"
}
]
},
{
"key": "secure",
"value": "false bool"
},
{
"key": "statusDetail",
"children": [
{
"key": "licenseKeyOptionList",
"children": [
{
"key": "licenseKeyOption",
"value": "conversion enum"
},
{
"key": "licenseKeyOption",
"value": "failover enum"
}
]
},
{
"key": "connectPort",
"value": 7999
}
]
},
{
"key": "rateProperties",
"children": [
{
"key": "rateDetail",
"children": [
{
"key": "largeReadRate",
"value": "0 MB/sec"
}
]
},
{
"key": "totalRate",
"value": "67.2446365356445 MB/sec"
}
]
},
{
"key": "online",
"value": "true bool"
},
{
"key": "cacheProperties",
"children": [
{
"key": "cacheDetail",
"children": [
{
"key": "tripleCachePartitions",
"children": [
{
"key": "tripleCachePartitionList",
"children": [
{
"key": "tripleCachePartition",
"children": [
{
"key": "partitionSize",
"value": 768
},
{
"key": "partitionBusy",
"value": 0
},
{
"key": "partitionUsed",
"value": 0
},
{
"key": "partitionFree",
"value": 100
}
]
}
]
}
]
}
]
}
]
}
]
}
]
You might have to run more tests, as what you require seems quite arbitrary, but I believe this function does what you are looking for. It works in a similar way to yours, by simply recursing the tree, and checking for object types, and if the special case is matched.
function toKeyValue(obj) {
return Object.keys(obj).map(k => {
var value = obj[k]
var key = k
var valueName = 'children'
if(Array.isArray(value)){
key = k + 'List'
value = value.map(toKeyValue)
}else if(value !== null && typeof value === 'object'){
// check for special case
if(Object.keys(value).sort().toString() === "units,value"){
value = value.value + ' ' + value.units
valueName = 'value'
}else{
value = toKeyValue(value)
}
}else{
valueName = 'value'
}
return {
key: key,
[valueName]: value
}
})
}
Fiddle here

Categories

Resources