Convert one Multidimensional JSON array to another - javascript

I have the following input object
{
"id": 1,
"isLeaf": false,
"name": "New rule",
"pid": 0,
"dragDisabled": true,
"children": [
{
"id": "new1",
"value": "data1",
"then": false,
"type": "set",
"forEach": false,
"pid": 1
},
{
"id": "new2",
"value": "data2",
"then": true,
"type": "if",
"forEach": false,
"pid": 1,
"children": [
{
"id": "new3",
"type": "Then",
"enableElse": true,
"pid": "new2",
"children": [
{
"id": "new5",
"value": "data3",
"then": false,
"type": "fuzzy_search",
"forEach": false,
"pid": "new3"
}
]
},
{
"id": "new4",
"type": "Else",
"enableElse": true,
"pid": "new2",
"children": [
{
"id": "new6",
"value": "data4",
"then": false,
"type": "return",
"forEach": false,
"pid": "new4"
}
]
}
]
}
]
}
I need to convert it into the following json
[
{
"id": "new1",
"condition": "data1"
},
{
"id": "new2",
"condition": "data2",
"then": [{
"id": "new5",
"condition": "data3"
}],
"else": [{
"id": "new6",
"condition": "data4"
}]
}
]
I have to recursively iterate through all existing inner child array of the input json array to formulate the output.
Following is the partially implemented code for the functionality.
ruleJSONFormatter = (request, parentItem, innerJSON) => {
try {
var outerObject = request;
if (outerObject.children && outerObject.children.length) {
var innerArray = outerObject.children;
// second iteration with inner children
innerArray.forEach((innerItem, index) => {
let parentObj = {};
let recursiveObj = {}; let thenArray = [];
recursiveObj['condition'] = innerItem.value && innerItem.value != undefined ? innerItem.value.formatedData : {};
recursiveObj['type'] = innerItem.type;
recursiveObj['id'] = innerItem.id;
recursiveObj['pid'] = innerItem.pid;
if (innerItem.children && innerItem.children != undefined && innerItem.children.length) {
switch (innerItem.type) {
case 'if':
recursiveObj['then'] = [];
recursiveObj['else'] = [];
}
if (Object.keys(parentObj).length == 0) {
parentObj = recursiveObj;
} else {
}
ruleJSONFormatter(innerItem, parentItem, parentObj)
} else {
if (Object.keys(parentObj).length == 0)
responseArray.push(innerJSON);
}
});
}
else {
console.log("No Values Inside the Formated Data ")
}
console.log("output-----------");
console.log(JSON.stringify(responseArray));
return responseArray
} catch (error) {
console.log('((((((((((((((((((((((((((', error)
}
}
final output array has a condition key which binds the value key from the input json and 'then' key which contains the multiple successive inner children array which is the success condition for type 'if' object. similar is the case for 'else' key in output
I find it hard to recursively call the same function to generate the desired output. the problem arises when there are deep nesting in the children array.Any help is appreciated.Thanks.

Related

Get all its parent nodes path for each child nodes

Hi I have below code running, but I would like to add one more property called path which should consist all its parent node path
Expected output I need something as I have shown for cardTtile, so I need same for each node.
[
{
"id": "cardShop",
"key": "cardShop",
"title": "cardShop",
"selectable": false,
"path":cardShop"
"children": [
{
"id": "cardData",
"key": "cardData",
"title": "cardData",
"parentId": "cardShop",
"path":cardShop.cardData"
"selectable": false,
"children": [
{
"id": "cardTitle",
"key": "cardTitle",
"title": "cardTitle",
"parentId": "cardData",
"path":cardShop.cardData.cardTitle"
"isLeaf": true
},
{
"id": "cardType",
"key": "cardType",
"title": "cardType",
"parentId": "cardData",
"isLeaf": true
},
{
"id": "dtmProductName",
"key": "dtmProductName",
"title": "dtmProductName",
"parentId": "cardData",
"isLeaf": true
},
{
"id": "viewAllCards",
"key": "viewAllCards",
"title": "viewAllCards",
"parentId": "cardData",
"selectable": false,
"children": [
{
"id": "url",
"key": "url",
"title": "url",
"parentId": "viewAllCards",
"isLeaf": true
},
{
"id": "text",
"key": "text",
"title": "text",
"parentId": "viewAllCards",
"isLeaf": true
}
]
}
]
},
{
"id": "eligibilityChecker",
"key": "eligibilityChecker",
"title": "eligibilityChecker",
"parentId": "cardShop",
"selectable": false,
"children": [
{
"id": "header",
"key": "header",
"title": "header",
"parentId": "eligibilityChecker",
"isLeaf": true
},
{
"id": "subHeader",
"key": "subHeader",
"title": "subHeader",
"parentId": "eligibilityChecker",
"isLeaf": true
},
{
"id": "bulletPoints",
"key": "bulletPoints",
"title": "bulletPoints",
"parentId": "eligibilityChecker",
"isLeaf": true
}
]
}
]
}
]
I have below running code example here. I tried to persist parentKey recursively but its not giving me expected output.
const transform = data => {
const loop = (data, parent) => Object.entries(data).map(([key, value]) => {
let additional = parent? {
parentId: parent
}:{}
if(typeof value === 'object' && !Array.isArray(value)){
additional = {
...additional,
selectable: false,
children: loop(value, key)
}
}else{
additional.isLeaf = true
}
return {
id: key,
key,
title: key,
...additional
}
})
return loop(data)
}
let jsonObj = {
"data": {
"cardShop": {
"cardData": {
"cardTitle": "The Platinum Card<sup>®</sup>",
"cardType": "credit-cards",
"dtmProductName": "PlatinumCard",
"viewAllCards": {
"url": "credit-cards/all-cards",
"text": "All Cards"
}
},
"eligibilityChecker": {
"header": "Check your eligibility",
"subHeader": "The Platinum Card®",
"bulletPoints": [
"Only takes a couple of minutes to complete",
"Will not impact your credit rating",
"Allows you to apply with confidence"
]
}
}
}
}
console.log(transform(jsonObj.data))
]
You suggestion would be appreciated
Thanks
You could take another variable for path and add the actual key to it.
const transform = data => {
const loop = (data, parentId, previousPath = '') => Object
.entries(data)
.map(([key, value]) => {
const
additional = parentId ? { parentId } : {},
path = previousPath + (previousPath && '.') + key;
Object.assign(
additional,
value && typeof value === 'object' && !Array.isArray(value)
? { selectable: false, children: loop(value, key, path) }
: { isLeaf: true }
);
return { id: key, key, title: key, path, ...additional };
});
return loop(data);
}
const data = { cardShop: { cardData: { cardTitle: "The Platinum Card<sup>®</sup>", cardType: "credit-cards", dtmProductName: "PlatinumCard", viewAllCards: { url: "credit-cards/all-cards", text: "All Cards" } }, eligibilityChecker: { header: "Check your eligibility", subHeader: "The Platinum Card®", bulletPoints: ["Only takes a couple of minutes to complete", "Will not impact your credit rating", "Allows you to apply with confidence"] } } };
console.log(transform(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Search for matches in an array of objects. JS

I have the following response from the server. I need to search this answer and compare it in turn with each field.
Example:
My task is that I know for sure that there should be 3 objects and each object has its own value for the type field, this is 'API', 'DEFAULT' or 'X'. How can you make it so that you can search for these three values ​​in the whole object and get an error if one of them is missing?
{
"result": [
{
"id": "54270522",
"key": "1-16UUC93PT",
"type": "API"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "DEFAULT"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "Х"
}
],
"success": true
}
You can first verify that the length is 3 and then loop over all the types and check if each one is present.
const data = {
"result": [
{
"id": "54270522",
"key": "1-16UUC93PT",
"type": "API"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "DEFAULT"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "Х"
}
],
"success": true
};
const requiredTypes = ['API', 'DEFAULT', 'Х'];
const types = new Set(data.result.map(({type})=>type));
const good = data.result.length === 3 && requiredTypes.every(type=>types.has(type));
console.log(good);
In case you would like to also know which value of those 3 are missing:
const check = (obj) => {
if (obj.result.length !== 3) return false;
let validTypes = ['API', 'DEFAULT', 'X'];
obj.result.forEach((r) => {
const index = validTypes.indexOf(r.type);
if (index !== -1) validTypes.splice(index, 1);
})
if (validTypes.length) return `${validTypes.join(', ')} is missing`;
return true;
};
So if you would have something like:
const test = {
"result": [
{
"id": "54270522",
"key": "1-16UUC93PT",
"type": "API"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "DEFAULT"
},
{
"id": "54270522",
"key": "3-1JOPPEIZI",
"type": "X2"
}
],
"success": true
}
and you call check(test) it will return "X is missing". If all three types are present in the object that gets passed into the check function, it will return true. Of course this can be adjusted as you need. More objects, different types etc...

How can I insert an object in an array of objects

I want to convert my object status field that is would be modified specifically.
I have found the answer but no fill my goal that's why I updated my question
I have objects like this below:
Items = [
{
"id": 9,
"alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1",
"name": "sfasf",
"status": 1
},
{
"id": 5,
"alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 2
},
{
"id": 6,
"alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 3
}
]
I need to convert my object like below or I need to print like belows:
[
{
"id": 9,
"alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1",
"name": "sfasf",
"status": {
"1": "ACTIVE"
}
},
{
"id": 5,
"alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": {
"2": "INACTIVE"
}
},
{
"id": 6,
"alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": {
"3": "DELETED"
}
}
]
For example:
const possibleStatus = {
1: 'ACTIVE',
2: 'INACTIVE'
}
Items.map(item => ({...item, status: {[item.status]: possibleStatus[item.status]}}))
Update: addded lookup via possibleStatus
If nullish coalescing operator ?? is available, I would add a fallback for undefined status:
Items.map(item => ({...item, status: {[item.status]: possibleStatus[item.status] ?? `UNDEFINED STATUS ${item.status}`}}))
but only if this is display logic. In case of business logic, I'd rather check for valid values and throw an exception, e.g. encapsulated in a function mapping the status string to the object.
let statusTable = {
1: "ACTIVE",
2: "INACTIVE",
3: "DELETED"
}
let Items = [
{
"id": 9,
"alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1",
"name": "sfasf",
"status": 1
},
{
"id": 5,
"alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 2
},
{
"id": 6,
"alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 3
}
]
let result = Items.map(el => {
el.status = { [el.status]: statusTable[el.status] }
return el;
})
console.log(result);
I hope this solution be useful for you.
Items = [
{
"id": 9,
"alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1",
"name": "sfasf",
"status": 1
},
{
"id": 5,
"alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 2
}
]
Items = Items.map(item => {
item.status = item.status == 1 ? { "1": "ACTIVE" } : { "2": "INACTIVE" }
return item;
} )
console.log(Items);
If this is json, first you might want to parse it with JSON.parse, like following:
let parse = JSON.parse(yourJsonObj)
Next you get your array, which you need to modify. You can use map method and return a new array with the data you need:
let newData = parse.map(item => {
item.status = { [item.status]: "INACTIVE" };
return item;
});
Then you can go back and stringify it back if needed with JSON.stringify(newData).
The rules by which you set INACTIVE or ACTIVE I don't know, but this is the gist of it.
As others have indicated, map() is the way to go.
I've stepped things out a little here in such a way that the system wouldn't have unintended consequences if a third property was introduced. The switch statement explicitly only changes things if the status is 1 or 2 and leaves things alone otherwise.
The other examples given are probably fine for your use case though.
var items = [ { "id": 9, "alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1", "name": "sfasf", "status": 1 }, { "id": 5, "alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98", "name": "Test", "status": 2 },
{
"id": 6,
"alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98",
"name": "Test",
"status": 3
} ];
const process = () => {
// render original
const orig = document.querySelector('.original');
orig.innerHTML = '';
items.forEach(i => orig.innerHTML += `<li>${i.status}</li>`);
var result = items.map(i => {
switch(i.status) {
case(1):
i.status = {"1": "ACTIVE"}
break;
case(2):
i.status = {"2": "INACTIVE"}
break;
case(3):
i.status = {"3": "DELETED"}
break;
default:
// if status is not 1, 2 or 3, do nothing to the object
break;
}
// return the object
return i
})
// render processed
const res = document.querySelector('.results');
res.innerHTML = '';
items.forEach(i => res.innerHTML +=
`<li>${JSON.stringify(i.status)}</li>`);
}
process()
<div class="cols">
<div>
<p>Original</p>
<ul class="original">
</ul>
</div>
<div>
<p>Result</p>
<ul class="results"></ul>
</div>

JavaScript / typescript: unable to regenerate object

I have an object as specified below:
{
"player settings": [
{
"id": 1,
"labelName": "site language",
"labelValue": [
{
"id": 1,
"languageName": "ARABIC",
"language": "لغتك",
"languageCode": "AE"
},
{
"id": 2,
"languageName": "CHINESE",
"language": "你的语言",
"languageCode": "ZH"
},
],
"dataType": "DD",
"selectedData": "2"
},
{
"id": 2,
"labelName": "subtitle language",
"labelValue": [
{
"id": 1,
"languageName": "ARABIC",
"language": "لغتك",
"languageCode": "AE"
},
{
"id": 2,
"languageName": "CHINESE",
"language": "你的语言",
"languageCode": "ZH"
},
],
"dataType": "DD",
"selectedData": "1"
},
]
},
{
"channel": [
{
"id": 11,
"labelName": "channel label",
"dataType": "TX",
"selectedData": "jhfh"
}
]
},
{
"others": [
{
"id": 16,
"labelName": "others label",
"dataType": "TX",
"selectedData": "dhgdhg"
}
]
}
How can I modify and re-generate the object with the following conditions:
if dataType === 'DD' then convert selectedData into number.
I wrote the below code but stuck here:
for (var j = 0; j < this.myobject.length; j++){
this.myobject.forEach(obj => {
console.log(obj)
});
}
You can use for..in
let data = {"player settings": [{"id": 1,"labelName": "site language","labelValue": [{"id": 1,"languageName": "ARABIC","language": "لغتك","languageCode": "AE"},{"id": 2,"languageName": "CHINESE","language": "你的语言","languageCode":"ZH"},],"dataType": "DD","selectedData": "2"},],"player settings2": [{"id": 1,"labelName": "site language","labelValue": [{"id": 1,"languageName": "ARABIC","language": "لغتك","languageCode": "AE"},{"id": 2,"languageName": "CHINESE","language": "你的语言","languageCode":"ZH"},],"dataType": "NO DD","selectedData": "2"},]}
for (let key in data) {
data[key].forEach(obj => {
if (obj.dataType === "DD") {
obj.selectedData = +(obj.selectedData || 0)
}
})
}
console.log(data)
Immutable approach
let data = {"player settings": [{"id": 1,"labelName": "site language","labelValue": [{"id": 1,"languageName": "ARABIC","language": "لغتك","languageCode": "AE"},{"id": 2,"languageName": "CHINESE","language": "你的语言","languageCode":"ZH"},],"dataType": "DD","selectedData": "2"},],"player settings2": [{"id": 1,"labelName": "site language","labelValue": [{"id": 1,"languageName": "ARABIC","language": "لغتك","languageCode": "AE"},{"id": 2,"languageName": "CHINESE","language": "你的语言","languageCode":"ZH"},],"dataType": "NO DD","selectedData": "2"},]}
let newObj = {}
for (let key in data) {
newObj[key] = data[key]
data[key].forEach(obj => {
if (obj.dataType === "DD") {
newObj.selectedData = +(obj.selectedData || 0)
}
})
}
console.log(newObj)
We can use filter on the main obj and then proceed modifying the object.
function modifyDataToNumber(){
let myObject = jsonObj['player settings'];
let ddMyObject = myObject.filter((row)=>(row["dataType"]==="DD"));
console.log(ddMyObject[0]["selectedData"]);
ddMyObject.forEach((row,index)=>{
ddMyObject[index]["selectedData"] = +ddMyObject[index]["selectedData"];
})
console.log(jsonObj);
}
modifyDataToNumber();
I would do something like this
const json = {
"player settings": [
{
"id": 1,
"labelName": "site language",
"labelValue": [
{
"id": 1,
"languageName": "ARABIC",
"language": "لغتك",
"languageCode": "AE"
},
{
"id": 2,
"languageName": "CHINESE",
"language": "你的语言",
"languageCode": "ZH"
},
],
"dataType": "DD",
"selectedData": "2"
},
]
};
json['player settings'] = json['player settings'].map(setting => {
if (setting.dataType === 'DD') {
const updatedSetting = {
...setting,
selectedData: parseInt(setting.selectedData)
};
return updatedSetting;
}
return setting;
});
console.log('Result', json);
Since you say "re-generate", I assume you want an immutable approach to this (that is, generate a copy of the data with the desired changes, rather than changing the original object).
To that, you can use spread syntax and Array#map:
let convertSetting = setting => ({
...setting,
selectedData: setting.dataType === "DD"
? parseInt(setting.selectedData)
: setting.selectedData
});
let convert = x => ({
...x,
["player settings"]: x["player settings"].map(convertSetting)
});
Then you can use that function as convert(yourOriginalObject).

Nesting a parent child relationship in lodash, given the parent id and children

How would I be able to nest json object if the parent and its children was given as a property.
The data looks like:
"1": {
"id": 1,
"name": "foo",
"parent": null,
"root": 1,
"children": [2, 4, 6],
"posts":[
{ "id": "1", "name": "item1" },
{ "id": "2", "name": "item2" },
{ "id": "3", "name": "item3" }
]
},
"2": {
"id": 2,
"name": "bar",
"parent": 1,
"root": 1,
"children": null,
"posts":[
{ "id": "4", "name": "item4" }
]
},
"3": {
"id": 3,
"name": "bazz",
"parent": null,
"root": 3,
"children": [5, 7],
"posts":[
{ "id": "5", "name": "item5" },
{ "id": "6", "name": "item6" }
]
},
....
A simple groupby using lodash won't do it.
var group = _.groupBy(data, 'parent');
Here is a fiddle:
http://jsfiddle.net/tzugzo8a/1/
The context of question is a nested categories with subcategories, and categories can have categories and posts in them.
Basically I don't want to have a different property for children and posts, since they are all children of a parent.
Desired output
"1": {
"id": 1,
"name": "foo",
"parent": null,
"root": 1,
"isCategory": true,
"children": [
{
"id": 2,
"name": "bar",
"parent": 1,
"root": 1,
"isCategory": true,
"children": null
},
{ "id": "1", "name": "item1", isCategory: false },
{ "id": "2", "name": "item2", isCategory: false },
{ "id": "3", "name": "item3", isCategory: false }
]
...
}
This is my take on the question (fiddle):
var data = getData();
var group = getTree(data);
console.log(group);
function getTree(flat) {
return _.reduce(flat, function (treeObj, item, prop, flatTree) {
var children = _.map(item.children, function (childId) {
return _.set(flatTree[childId], 'isCategory', true);
}).concat(_.map(item.items, function(item) {
return _.set(item, 'isCategory', false);
}));
item.children = !!children.length ? children : null;
delete item.items;
item.parent === null && (treeObj[prop] = item);
return treeObj;
}, {});
}
Take a look on the updated fiddle:
var data = getData();
_.keys(data).forEach(function(id){
var element = data[id];
if (element.children === null){
element.children = [];
}
element.isCategory = true;
element.items.forEach(function(item){
item.isCategory = false;
})
});
_.keys(data).forEach(function(id){
var element = data[id];
element.children = element.children.map(function(childId){
return data[childId];
}).concat(element.items);
});
_.keys(data).forEach(function(id){
delete data[id].items;
});
console.log(JSON.stringify(_.findWhere(_.values(data), {'parent': null})));

Categories

Resources