I'm trying to convert the below JSON to another format wherein the reultant JSON dosen't contain valueChainEntity object name and also I want to delete the inputs and outputs array.Note that the structure is a parent child relation and the inputs and outputs array can be present inside the items array at any level.Even in the all levels(but only inside items array)
var inputJSON = [
{
"valueChainEntity":{
"id":308,
"valueChainEntityId":48,
"items":[
{
"valueChainEntity":{
"id":309,
"valueChainEntityId":49,
"items":[
{
"valueChainEntity":{
"id":312,
"valueChainEntityId":50,
"items":[
]
},
"inputs":[
{
"id":312,
"valueChainEntityId":50,
"items":[
]
}
],
"outputs":[
{
"id":313,
"valueChainEntityId":50
}
]
}
]
}
}
]
}
}
]
var outputJSON= [
{
"id":308,
"valueChainEntityId":48,
"items":[
{
"id":309,
"valueChainEntityId":49,
"items":[
{
"id":312,
"valueChainEntityId":50,
"items":[
]
}
]
}
]
}
]
My code:
inputJSON.forEach((item) => {
return item.valueChainEntity;
});
//which will traverse only through the first level and will not delete the **inputs** and **outputs** array..
See if following works:
function parseInputJSON(inp) {
return inp.map(function (item) {
return getValueChainEntity(item);
});
}
function getValueChainEntity(item) {
if (item['valueChainEntity'] != undefined) {
var valueChainEntity = item.valueChainEntity;
valueChainEntity.items = parseInputJSON(valueChainEntity.items);
return valueChainEntity;
}
return item;
}
var inputJSON=[
{
"valueChainEntity": {
"id": 308,
"valueChainEntityId": 48,
"items": [
{
"valueChainEntity": {
"id": 309,
"valueChainEntityId": 49,
"items": [
{
"valueChainEntity": {
"id": 312,
"valueChainEntityId": 50,
"items": []
},
"inputs": [
{
"id": 312,
"valueChainEntityId": 50,
"items": []
}
],
"outputs": [
{
"id": 313,
"valueChainEntityId": 50
}
]
}
]
}
}
]
}
}];
var newInput = parseInputJSON(inputJSON);
document.getElementById("json").innerHTML = JSON.stringify(newInput, undefined, 4);
<pre id="json"></pre>
Here's another way that is working..
Sample code
function populateChildrenRecursively(outputTypeId, valueChainEntities, parentValueChainEntity) {
for (var i = 0; i < valueChainEntities.length; i++) {
if (valueChainEntities[i].valueChainEntity.valueChainEntityId != parentValueChainEntity.valueChainEntity.valueChainEntityId && hasInput(outputTypeId, valueChainEntities[i].inputs)) {
parentValueChainEntity.valueChainEntity.items.push(valueChainEntities[i]);
if (valueChainEntities[i].outputs.length > 0) {
valueChainEntities[i].valueChainEntity.items = [];
for (var j = 0; j < valueChainEntities[i].outputs.length; j++) {
populateChildrenRecursively(valueChainEntities[i].outputs[j].outputTypeId, valueChainEntities, valueChainEntities[i]);
}
}
}
}
}
https://plnkr.co/edit/d2wtXcaU37quthBjgrCu?p=preview
Related
I need to restructure a nested JSON data.
Here is how it looks like:
{
"MainKey1": [
{
"Section1": {
"ParentTag1 Mapped Label": {
"ParentTag1": {
"Tag1 Mapped Label": {
"Tag1": "1234567890"
}
}
}
}
},
{
"Section2": {
"ParentTag1 Mapped Label": {
"ParentTag1": {
"Tag1 Label": {
"Tag1": "111222333444"
},
"Tag2 Label": {
"Tag2": "121212"
},
"Tag3 Label": {
"Tag3": "0987654321"
}
}
}
}
}
],
"MainKey2": [
{
"Section1": {
"ParentTag1 Mapped Label": {
"ParentTag1": {
"Tag1 Mapped Label": {
"Tag1": "1234567890"
}
}
}
}
}
]
}
And this is a sample of the converted JSON:
{
MainKey: [
{
Section1: [
{
ParentTag1: [
{ Tag1: "1234567890" }
]
}
]
},
{
Section2: [
{
ParentTag1: [
{ Tag1: "111222333444" },
{ Tag2: "121212" },
{ Tag3: "0987654321" }
]
}
]
}
],
MainKey2: [
{
Section1: [
{
ParentTag1 : [
{ Tag1: "1234567890" }
]
}
]
}
]
}
Rules:
Everything inside a MainKey (outermost keys, could be any name) should be an array
All labels should be stripped (as the label could be any name, without the actual word "Label", we can determine if it is a label based on the depth level. Since the JSON will have the label as the parent and the actual "tag" as a child.
Here is what I currently have (it is a mess, sorry!)
function convertJson (jsonObj) {
const mainKeys = Object.keys(jsonObj)
let output = {}
for (let i = 0; i < mainKeys.length; i++) {
const mainKey = mainKeys[i]
let result = []
output[mainKey] = result
for (let j = 0; j < jsonObj[mainKey].length; j++) {
const innerObj = {...jsonObj[mainKey][j]}
const sectionName = Object.keys(innerObj)[0]
const sectionObj = {}
sectionObj[sectionName] = []
const index = result.push(sectionObj) - 1
parseObj(innerObj[sectionName], result[index], 0) // if I change 2nd param to: result, it generates incorrect output
}
}
console.log(output)
}
function parseObj (innerObj, result, depthCount) {
for (var key in innerObj) {
if (typeof innerObj[key] === "object") {
if (depthCount % 2 === 1) {
const parentObj = {}
parentObj[key] = []
result.push(parentObj)
depthCount++
parseObj(innerObj[key], parentObj[key], depthCount)
} else {
depthCount++
parseObj(innerObj[key], result, depthCount)
}
} else {
const keyValuePairObj = {}
keyValuePairObj[key] = innerObj[key]
result.push(keyValuePairObj)
}
}
return result
}
convertJson(json)
But it generates an error:
Uncaught TypeError: result.push is not a function
Now if I change line 90 from:
parseObj(innerObj[sectionName], result[index], 0)
to:
parseObj(innerObj[sectionName], result, 0)
Here is incorrect output:
{
"MainKey1": [
{
"Section1": []
},
{
"ParentTag1": [
{
"Tag1": "1234567890"
}
]
},
{
"Section2": []
},
{
"ParentTag1": [
{
"Tag1": "111222333444"
},
{
"Tag2 Label": [
{
"Tag2": "121212"
}
]
},
{
"Tag3": "0987654321"
}
]
}
],
"MainKey2": [
{
"Section1": []
},
{
"Tag1": "1234567890"
}
]
}
And here is my fiddle:
https://jsfiddle.net/kzaiwo/L4avxmyd/36/
Thanks a lot! Appreciate any help!
I have a data array
var data=[{
"key": "KUZEY",
"items": [
{
"key": "MARMARA",
"items": [
{
"key": "T100",
"items": [
{
"Ref": 1,
"ApprovedReserveQuantity": 1
}
]
}
]
},
{
"key": "MARMARA 2",
"items": [
{
"key": "T100",
"items": [
{
"Ref": 2,
"ApprovedReserveQuantity": 1
}
]
}
]
}
] }]
İ want to get items when i call function. how can do that recursiveMethod?
groupedItems=recursiveMethod(data)
groupedItems==>[{"Ref": 1,"ApprovedReserveQuantity": 1},{"Ref": 2,"ApprovedReserveQuantity": 1}]
groupedItems:any[]=[];
recursiveMethod(element){
if(element.items==null)
this.groupedItems.push(element)
if (element.items != null){
let i;
for(i=0; i < element.items.length; i++){
this.recursiveMethod(element.items[i]);
}
}
}
it's worked
Couldn't find any 'key' checking in your answer.
Even though I don't trust my function completely, and am confused for as why it worked, It can be reusable if you tweak/adjust it.
const extractInnermostByKey = (data, targetKey, res = []) => {
data.forEach((obj) => {
for (let key of Object.keys(obj)) {
if (key === targetKey) {
// console.log(res); observe res
res.shift();
res.push(...obj[key]);
return extractInnermostByKey(res, targetKey, res);
}
}
});
return res;
};
const groupedItems = extractInnermostByKey(data, 'items');
console.log(groupedItems);
i have an array of objects of the below format
each with a unique 'sub-task' entry, each of this sub-task is to be embedded as a children element of each unique 'task' from the 'tasks' array
[
{
"sub-task":"abc",
"task":"alpha1"},
{
"sub-task":"def",
"task":"alpha1"},
{
"sub-task":"ijkl",
"task":"proto"},
{
"sub-task":"mno",
"task":"def"},
{
"sub-task":"qrs",
"task":"proto"},
{
"sub-task":"asdf",
"task":"mno"},
]
i was trying to frame an another array of below format
[
{
"name":"alpha1",
"children":[
{
"name":"abc"
},
{
"name":"def",
"children":[
{
"name":"mno"
}
]
}
]
},
{
"name":"proto",
"children":[
{
"name":"ijkl"
},
{
"name":"qrs",
"children":[
{
"name":"asdf"
}
]
}
]
}
]
i was trying of below logic, but ended up with no solution...
var treeData = [];
for( var ele of tasks){
recurOn(treeData,ele);
}
function recurOn(arr,obj){
if(arr.length == 0){
treeData.push({name:obj.parentGroup,children:[{name:obj.groupName}]})
//console.log(treeData);
return 1;
}else {
for(var item of treeData){
if(item.name == obj.parentGroup){
//console.log('item: ', item);
item.children.push({name:obj.groupName});
break;
}
else {
treeData.push(recurOn([],obj))
}
}
return 1;
}
}
//console.log(treeData);
//console.log(result);
Since the no of levels an elements holds is not known i was unable to fix for a logic
Use a map to store object reference.
let input = [
{ "sub-task": "abc", "task": "alpha1" },
{ "sub-task": "def", "task": "alpha1" },
{ "sub-task": "ijkl", "task": "proto" },
{ "sub-task": "mno", "task": "def" },
{ "sub-task": "qrs", "task": "proto" },
{ "sub-task": "asdf", "task": "mno" },
];
let map = new Map, result = [];
input.forEach(({ ["sub-task"]: name, task }) => {
let node = map.get(task), child = { name, children: [] };
if (!node) {
map.set(task, node = { name: task, children: [] });
result.push(node);
}
map.set(name, child);
node.children.push(child);
})
console.log(result);
I have following Json which i need to insert into a table.
I want to convert each student detail into a row.
Because if i loop through the rows as per the existing structure i am reading one column as a row.
var json {
"Students":[
{
"name":{
"value":"Allan"
},
"number":{
"value":"123"
}
},
{
"name":{
"value":"Frank"
},
"number":{
"value":"456"
}
}
]
}
Ideally i want to the above as
{ "name": "Allan", "number": 123};
{ "name": "Frank", "number": 456};
I am looping through the Json as below
var objectKeys = Object.keys(json);
for (var key in objectKeys)
{
var student = json.Students;
for (var i = 0; i < student .length; i++) {
for (var column in json.Students[i]) {
window.print(column);
window.print(json.Students[i][column].value);
}
}
}
NOTE: No JQuery, want to achieve the above through normal Javascript.
If you want to transform the data, you can use Array.map
var json = {"Students":[{"name":{"value":"Allan"},"number":{"value":"123"}},{"name":{"value":"Frank"},"number":{"value":"456"}}]};
let result = json.Students.map(o => ({
name: o.name.value,
number: o.number.value
}));
console.log(result);
If you want to access the data, you can use Array.forEach
var json = {"Students":[{"name":{"value":"Allan"},"number":{"value":"123"}},{"name":{"value":"Frank"},"number":{"value":"456"}}]};
json.Students.forEach(o => console.log({name: o.name.value, number: o.number.value}));
var json = {
"Students":[
{
"name":{
"value":"Allan"
},
"number":{
"value":"123"
}
},
{
"name":{
"value":"Frank"
},
"number":{
"value":"456"
}
}
]
}
var studentData = JSON.stringify(json.Students);
var convertedData = JSON.parse(studentData.replace(/\{\"value\"\:/g,"").replace(/\}\,\"number/g,',"number').replace(/\"\}\}/g,'"}'));
Try this :)
No map or reduce. Just classic Javascript.
var json = {
"Students": [{
"name": {
"value": "Allan"
},
"number": {
"value": "123"
}
},
{
"name": {
"value": "Frank"
},
"number": {
"value": "456"
}
}
]
};
for (var student of json["Students"]) {
console.log(student); //your logic goes here.
}
Is there is a way to transform this JSON Object using Angular? I need to transform the JSON object from this format:
$scope.TestJson = {
"filters": [
{
"dataPropertyID": "VoidType",
"label": "Homeless"
},
{
"dataPropertyID": "VoidType",
"label": "Mainstream"
},
{
"dataPropertyID": "PropertyType",
"label": "Flat"
},
{
"dataPropertyID": "PropertyType",
"label": "Cottage"
}
]
}
To this format:
$scope.NewTestJson = {
"filters": [
{
"dataPropertyID": "VoidType",
"label":[ "Homeless","Mainstream"]
},
{
"dataPropertyID": "PropertyType",
"label":[ "Flat", "Cottage"]
}
]
}
I think this is more a JavaScript question than anything else. Nonetheless:
$scope.NewTestJson = {
filters: [];
};
// Do something for all (old) filter items
$scope.TestJson.filters.forEach(function(filter) {
// Try to get the existing (new) filter
var newFilter = $scope.NewTestJson.filters.filter(function(newFilter) {
return newFilter.dataPropertyID === filter.dataPropertyID;
}).shift();
// If the new filter does not exist, create it
if (!newFilter) {
newFilter = {
dataPropertyID: filter.dataPropertyID,
label: []
};
$scope.NewTestJson.filters.push(newFilter);
}
// Finally, add the old filter label to the new filter
newFilter.label.push(filter.label);
});
json = {
"filters": [
{
"dataPropertyID": "VoidType",
"label": "Homeless"
},
{
"dataPropertyID": "VoidType",
"label": "Mainstream"
},
{
"dataPropertyID": "PropertyType",
"label": "Flat"
},
{
"dataPropertyID": "PropertyType",
"label": "Cottage"
}
]
};
newJson = new Object();
newJson.filters = new Array();
for (var element in json.filters) {
var check = 0;
for (var element2 in newJson.filters) {
if (json.filters[element].dataPropertyID === newJson.filters[element2].dataPropertyID) {
newJson.filters[element2].label.push(json.filters[element].label);
check = 1;
}
}
if (check == 0) {
var Obj = new Object();
Obj.dataPropertyID = json.filters[element].dataPropertyID;
Obj.label = new Array();
Obj.label.push(json.filters[element].label);
newJson.filters.push(Obj);
}
}