Fetch particular data from nested json using MVC in backbone.js - javascript

I know to work out simple concepts using backbone.js.below is my nested json file
{
"Re":
{
"Si":
[
{
"Def":
{
"StName": "Gau00",
"SID": "1",
"Parent": "",
"ParentID": "",
"Ty": "GAU",
"TypID": "2"
},
"Entities":
[
{
"EntityId": "2003",
"Index": "1",
"Value": "00"
},
{
"EntityId": "2006",
"Index": "1",
"Value": "B"
},
{
"EntityId": "2004",
"Index": "1",
"Value": "B"
},
{
"EntityId": "5",
"Index": "1",
"Value": "54"
},
{
"EntityId": "9007",
"Index": "1",
"Value": "1"
},
{
"EntityId": "9703",
"Index": "1",
"Value": "0"
}
],
"Connections":
[
{
"SourceID": "2",
"DestinationID": "1"
}
]
},
{
"Def":
{
"StName": "Tan",
"ID": "2",
"Parent": "",
"ParentID": "",
"Ty": "TA",
"TypID": "3"
},
"Entities": "",
"Connections":
[
{
"SourceElementID": "5",
"DestinationID": "2"
},
{
"SourceID": "2",
"DestinationID": "1"
}
]
}
]
}
}
Now with the StName i have to get all the other details from this nested json using backbone.js.Can anyone help me with ideas.

First convert JSON string to Javascript Object then use the following algorithm:
for each element in "Si":
if element["Def"]:
if element["Def"]["StName"] == "YOUR REQUIRED VALUE":
return element["Def"]
Write a function that takes your object, and iterate through the object and check StName with your required value. If condition true, return the current object.

Related

How can I accurately return nested values from JSON for comparison and then complete the comparison?

I have asked a similar question before but I've not been able to expand on this and I haven't found the exact answer that would teach me how to do this. My JSON file will have the same structure in terms of the element names inside each nested object but the values will vary. In plain English, I want to start at the bottom of the file and return true if the following conditions occur and stop searching if true: AppStatus is one of these ["Approved", "Auto Approved", "Return"] and the nested keys of "Name": "Payments", "Value": "X" and "Name": "Term", "Value": "Y" have values that don't match. I'm providing a snippet of the JSON so you can see more easily. The AppStatus is 2nd level and the Name, Value are 3rd level. In this example, it should return true based on the 2nd set of data in DataElements.
{
"DecisionHistory": [
{
"Id": "273601",
"Number": "1",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [
{
"Id": "213922",
"Name": "Payments",
"Value": "72",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
},
{
"Id": "273601",
"Number": "2",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [
{
"Id": "213922",
"Name": "Payments",
"Value": "72",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
},
{
"Id": "273601",
"Number": "3",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [
{
"Id": "213922",
"Name": "Payments",
"Value": "75",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
}
]
}
I've tried using 2 ugly nested for loops without success. I would prefer not to use for loops if I don't have to. See below:
function main(jsonFile) {
const history = JSON.parse(jsonFile).DecisionHistory;
const appStatus = ["Approved", "Auto Approved", "Return"];
const termMonths = "TermMonths";
const numberOfPayments = "Number of Payments";
let termMonthsVal = 0;
let numberofPaymentsVal = 0;
for (let a = history.length - 1; a >= 0; a--) {
if (appStatus.includes(history[a].AppStatus)) {
var dataElementsA = history[a].DataElements;
for (let b = (dataElementsA.length) - 1; b >= 0; b--) {
if (dataElementsA[b].Name == termMonths) {
termMonthsVal = new Number((dataElementsA[b].Value));
break;
}
}
}
}
for (let a = history.length - 1; a >= 0; a--) {
if (appStatus.includes(history[a].AppStatus)) {
var dataElementsB = history[a].DataElements;
for (let b = (dataElementsB.length) - 1; b >= 0; b--) {
if (dataElementsB[b].Name == numberOfPayments) {
numberofPaymentsVal = new Number((dataElementsB[b].Value));
break;
}
}
}
}
return (termMonthsVal != numberofPaymentsVal);
}
let jsonFile = `{
"DecisionHistory": [{
"Id": "273601",
"Number": "1",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [{
"Id": "213922",
"Name": "Payments",
"Value": "72",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
},
{
"Id": "273601",
"Number": "2",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [{
"Id": "213922",
"Name": "Payments",
"Value": "72",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
},
{
"Id": "273601",
"Number": "3",
"CreateDate": "2022-10-13 15:31:18.683",
"AppStatus": "Approved",
"DataElements": [{
"Id": "213922",
"Name": "Payments",
"Value": "75",
"GroupId": "12",
"CustomLabel": null
},
{
"Id": "990",
"Name": "Decisioned By",
"Value": "ASDF",
"GroupId": "3",
"CustomLabel": null
},
{
"Id": "215337",
"Name": "Term",
"Value": "75",
"GroupId": "13",
"CustomLabel": null
}
]
}
]
}`;
console.log(main(jsonFile));
//var result = main("_inJson");
//module.exports = main;
As a side note, the jsonFile in the main function is read in from a resource folder in my VS Code and I'm exporting main to an app.js so I can run assertions against it. So the JSON posted here is actually in a separate file but this is the exact structure of the data.
What am I missing? .filter? .map? .reduce? Differnt breaks?
Here's a "one-liner" depending on how long you want your lines to be ;)
const x = {
"DecisionHistory": [
{
"AppStatus": "Approved",
"DataElements": [
{
"Name": "Payments",
"Value": "72",
},
{
"Name": "Decisioned By",
"Value": "ASDF",
},
{
"Name": "Term",
"Value": "75",
}
]
},
{
"AppStatus": "Approved",
"DataElements": [
{
"Name": "Payments",
"Value": "72",
},
{
"Name": "Decisioned By",
"Value": "ASDF",
},
{
"Name": "Term",
"Value": "75",
}
]
},
{
"AppStatus": "Approved",
"DataElements": [
{
"Name": "Payments",
"Value": "75",
},
{
"Name": "Decisioned By",
"Value": "ASDF",
},
{
"Name": "Term",
"Value": "75",
}
]
}
]
};
const bar = (f) =>
f.DecisionHistory.reverse().some((decision) => ["Approved", "Auto Approved", "Return"].includes(decision.AppStatus) && decision.DataElements.find((el) => el.Name === 'Payments')?.Value !== decision.DataElements.find((el) => el.Name === 'Term')?.Value);
console.log(bar(x));

Use Normalizr with deeply nested array in JSON

I'm struggling to find a way to normalize this deeply nested JSON from an API response. Most documentation and resources have examples with a relatively flat structure.
{
"data": {
"id": "websites",
"type": "table",
"attributes": {
"data": [
{
"name": "facebook.com",
"id": "1",
...
},
{
"name": "google.com",
"id": "2",
...
},
{
"name": "twitter.com",
"id": "3",
...
{
]
}
}
}
My desired output would be:
{
entities: {
"1": {
"name": "facebook.com",
"id": "1",
...
},
"2": {
"name": "google.com",
"id": "2",
...
},
"3": {
"name": "twitter.com",
"id": "3",
...
}
},
results: ["1", "2", "3"]
}

I want to change a json format after fetching using javascript

I have a json like below..after fetching this json i stored in one variable called data.I need to change this data variable as bellow
{
"recipes": [
{
"cuisine": "chinese",
"description": "hjkhdkd",
"id": 3,
"min_time": "30-60min",
"name": "Noodles",
"nutrition": "",
"qty": "",
"quantity_unit_id": "2",
"rate": "",
"recipe_type": "vegetarian",
"serve": [
"4"
],
"tip": "",
"image_url": {
"medium": "/system/recipes/images/000/000/003/medium/dfdfs.jpeg?1501851554"
}
}
]
}
how i can change above json data like bellow using javascript
[
{
"cuisine": "chinese",
"description": "hjkhdkd",
"id": 3,
"min_time": "30-60min",
"name": "Noodles",
"nutrition": "",
"qty": "",
"quantity_unit_id": "2",
"rate": "",
"recipe_type": "vegetarian",
"serve": [
"4"
],
"tip": "",
"image_url": {
"medium": "/system/recipes/images/000/000/003/medium/dfdfs.jpeg?1501851554"
}
}
]
var data = '{ "recipes": [ { "cuisine": "chinese", "description": "hjkhdkd", "id": 3, "min_time": "30-60min", "name": "Noodles", "nutrition": "", "qty": "", "quantity_unit_id": "2", "rate": "", "recipe_type": "vegetarian", "serve": [ "4" ], "tip": "", "image_url": { "medium": "/system/recipes/images/000/000/003/medium/dfdfs.jpeg?1501851554" } } ] }';
var jsonifieddata = JSON.parse(data);
var newdata = jsonifieddata.recipes;
JSON.stringify(newdata);
Run this in your console.
A suggestion: share some effort you have made when you ask on stackoverflow again.

Remove an associate object while looping through using map

I have a json array and i need to delete the subarray whose id value is 5, which is falling under the serialNo 1. I tried the following method, but its not deleting any entry in the subarray.
let Details = [
{ "serialNo": "1", "text": "AAA", "subArray": [{ "id": "1", "name": "geo" }, { "id": "5", "name": "gau" }, { "id": "4", "name": "joi" }] },
{ "serialNo": "2", "text": "BBB", "subArray": [{ "id": "7", "name": "rom" }, { "id": "5", "name": "dom" }, { "id": "4", "name": "noi" }] },
{ "serialNo": "3", "text": "CCC", "subArray": [{ "id": "1", "name": "glo" }, { "id": "5", "name": "gum" }, { "id": "4", "name": "lom" }] }
];
Details.map((data) => {
if (data.serialNo === "1") {
data.subArray.map((subDetails) => {
if (subDetails.id === "5") {
delete data.subArray[subDetails];
}
})
}
})
I don't know why you explicitely wants to use the map function. But the following works:
let Details = [
{ "serialNo": "1", "text": "AAA", "subArray": [{ "id": "1", "name": "geo" }, { "id": "5", "name": "gau" }, { "id": "4", "name": "joi" }] },
{ "serialNo": "2", "text": "BBB", "subArray": [{ "id": "7", "name": "rom" }, { "id": "5", "name": "dom" }, { "id": "4", "name": "noi" }] },
{ "serialNo": "3", "text": "CCC", "subArray": [{ "id": "1", "name": "glo" }, { "id": "5", "name": "gum" }, { "id": "4", "name": "lom" }] }
];
Details = Details.map(function (data) {
if (data.serialNo === "1") {
data.subArray = data.subArray.filter(function (sa) {
return (sa.id !== "5");
});
}
return data;
});
console.log(Details);
The first problem is that you're not returning anything from the map functions. The second problem is that data.subArray[subDetails] is undefined, subDetails is an object not an index in the data.subArray array. You can use a combination of map and filter to accomplished this instead of using delete.
let Details = [
{ "serialNo": "1", "text": "AAA", "subArray": [{ "id": "1", "name": "geo" }, { "id": "5", "name": "gau" }, { "id": "4", "name": "joi" }] },
{ "serialNo": "2", "text": "BBB", "subArray": [{ "id": "7", "name": "rom" }, { "id": "5", "name": "dom" }, { "id": "4", "name": "noi" }] },
{ "serialNo": "3", "text": "CCC", "subArray": [{ "id": "1", "name": "glo" }, { "id": "5", "name": "gum" }, { "id": "4", "name": "lom" }] }
];
Details.map((data) => {
if (data.serialNo === "1") {
data.subArray = data.subArray.filter((subDetails) => {
return subDetails.id !== "5";
})
}
return data;
});
console.log(Details);
If you want to stick with map what you need to do is to return undefined when subDetails.id is 5.
let Details = [
{ "serialNo": "1", "text": "AAA", "subArray": [{ "id": "1", "name": "geo" }, { "id": "5", "name": "gau" }, { "id": "4", "name": "joi" }] },
{ "serialNo": "2", "text": "BBB", "subArray": [{ "id": "7", "name": "rom" }, { "id": "5", "name": "dom" }, { "id": "4", "name": "noi" }] },
{ "serialNo": "3", "text": "CCC", "subArray": [{ "id": "1", "name": "glo" }, { "id": "5", "name": "gum" }, { "id": "4", "name": "lom" }] }
];
Details.map((data) => {
if (data.serialNo === "1") {
data.subArray = data.subArray.filter((subDetails) => {
return subDetails.id === "5" ? undefined : subDetails;
})
}
return data;
});
console.log(Details);
One map plus object constructor:
const arr = [
{ "serialNo": "1", "text": "AAA", "subArray": [{ "id": "1", "name": "geo" }, { "id": "5", "name": "gau" }, { "id": "4", "name": "joi" }] },
{ "serialNo": "2", "text": "BBB", "subArray": [{ "id": "7", "name": "rom" }, { "id": "5", "name": "dom" }, { "id": "4", "name": "noi" }] },
{ "serialNo": "3", "text": "CCC", "subArray": [{ "id": "1", "name": "glo" }, { "id": "5", "name": "gum" }, { "id": "4", "name": "lom" }] }
];
const s = 1, id = 5; // conditions
const r = arr.map(e => (e.serialNo == s)
? Object.assign(e, {'subArray': e.subArray.filter(a => a.id != id)})
: e);
console.log(JSON.stringify(r, null, 2));
Object.assign swaps old subArray with the new filtered one.

how to get matching objects in an array of objects?

This is my object. Inside the bun array I have 2 objects. I need to access only "oid": 1 and "bid": 1 object details. There is no need to access the second object.
{
"oid": "1",
"oname": "Fon",
"bun": [{
"bid": "1",
"bname": "Ets",
"dep": [{
"did": "1",
"dname": "Dptment",
"pids": [{
"pid": "1",
"st": "active"
}, {
"pid": "2",
"st": "active"
}]
}]
}, {
"bid": "2",
"bname": "US",
"description": "unit2",
"dep": []
}]
}
How it is possible?
One way to achieve is using filter.
let jsObj = {
"oid": "1",
"oname": "Fon",
"bun": [{
"bid": "1",
"bname": "Ets",
"dep": [{
"did": "1",
"dname": "Dptment",
"pids": [{
"pid": "1",
"st": "active"
}, {
"pid": "2",
"st": "active"
}]
}]
}, {
"bid": "2",
"bname": "US",
"description": "unit2",
"dep": []
}]
};
jsObj.bun.filter((b) => {
return b.bid == 1
});

Categories

Resources