Array of JavaScript objects from JSON - javascript

I have a deeply nested JSON structure as below:
[
{
"ATA": "49",
"Description": "APU",
"MSI": "",
"Level":"1",
"ChildNodes": {
"Nodes": [
{
"ATA": "49-10",
"Description": "Power Plant",
"MSI": "",
"Level":"2",
"ChildNodes": {
"Nodes": [
{
"ATA": "49-13",
"Description": "APU Mounts",
"MSI": "Yes",
"Level":"3",
"ChildNodes": {
"Nodes": [
{
"ATA": "49-13-01",
"Description": "APU Gearbox Mount Bracket",
"MSI": "Yes",
"Level":"4"
}]
}
}
]
}
}
]
}
}
]
I'm trying to convert the following into an array of the form for easier processing of this data to show in a tabular format:
[{ATA:"49",Description:"APU",MSI:""},{ATA:"49-10",Description:"PowerPlant",MSI:""}]...
I've tried a lot of ways and though I can get all the key / value pairs, I can't figure out how to do this. I can't change the JSON since all the child nodes have dependencies. Any ideas?
Edit: I tried the following solution to get all key / value pairs: Traverse all the Nodes of a JSON Object Tree with JavaScript but I can't find out when to start a new object.

You should use a recursive function for this:
function processNodes(nodes, output){
for (var i = 0, l = nodes.length; i < l; ++i){
output.push({
"ATA": nodes[i]["ATA"],
"Description": nodes[i]["Description"],
"MSI": nodes[i]["MSI"]
});
if (nodes[i]["ChildNodes"]){
processNodes(nodes[i]["ChildNodes"]["Nodes"], output);
}
}
}
Then:
var json = JSON.parse( ... );
var output = [];
processNodes(json, output);
console.log(output);

Related

Exporting nested JSON to Excel in react

I am trying to export nested json to excel with specific format in react. I found few solution with XLSX which print only root node but I would also like to print nested nodes. Here is my JSON
[
{
"Root":"00000",
"RootId":"b597b7be58b0",
"Index":0,
"Child":[
{
"ChildId":"48bb0b4be689",
"Name":"Dimension",
"Index":0,
"SubChild0":[
{
"SubChildId":"6b620696cf35",
"Label":"Sample 2",
"Index":1
},
{
"SubChildId1":"f6b620696cf38",
"Label":"Sample 2",
"Index":2
}
]
},
{
"ChildId-01":"dcf70d3a-60b3-4b8c-8740-48bb0b4be689",
"Name":"Weight",
"Index":0,
"SubChild1":[
{
"SubChildId":"f42d99f5-37c5-4ea3-8425-6b620696cf35",
"Label":"Sample 2",
"Index":1
},
{
"SubChildId1":"f42d99f5-37c5-4ea3-8425-6b620696cf35",
"Label":"Sample 2",
"Index":2
}
]
}
]
}
]
and I would like to print in excel something like below format
I've never used any libraries that would help with your problem so cannot suggest any.
Your source data can be processed using javascript.
Your data almost fits a regular nested list with children, so creating a recursive function to process the data into something that can be interpreted as a CSV shouldn't be too difficult.
Your data has different tags so is a little more complicated.
The example below wont work for your data as-is. But it might give you an idea of where to start?
// source data with uniform keys in child objects
let data = [
{
"name": "root1",
"label": "root label",
"children": [
{
"name": "root1child1",
"label": "root1 child1 label",
"children": [
{
"name": "root1child1subchild1",
"label": "root1 child1 subchild1 label"
},
{
"name": "root1child1subchild2",
"label": "root1 child1 subchild2 label"
}
]
},
{
"name": "root1child2",
"label": "my label",
"children": [
{
"name": "root1child2subchild1",
"label": "root1 child2 subchild1 label"
},
{
"name": "root1child2subchild2",
"label": "root1 child2 subchild2 label"
}
]
}
]
}
]
let result = []
function process(node,padding) {
for (let i = 0, l = node.length; i<l; i++) {
result.push(Array(padding).concat("name", node[i].name))
result.push(Array(padding).concat("label", node[i].label))
if (node[i].children) {
// process the child node and pad the result to the right
process(node[i].children,++padding)
}
// reset padding and continue with next
--padding
}
}
// start processing the data
process(data,0)
// print the result as a table to the console
console.table(result)

Parsing nested JSON using JSON Schema or Classes

I have a large nested JSON response in following sample format:
{
"type": "folder",
"path": "Path1",
"owner": "user1",
"entries": [{
"type": "folder",
"path": "Path2",
"owner": "user1",
"entries": [{
"type": "folder",
"path": "Path3",
"owner": "user1"
},
{
"type": "file",
"path": "FullFilePath1",
"owner": "user1"
}
]
}]
}
I wanted to extract all the file type with selected keys and also add additional keys:
{
"type": "file",
"path": "FullFilePath1",
"Application": "My Application",
"UpdatedTime": "Time"
}
I am using nodejs. I need inputs in parsing the JSON file in best way. I was trying to check if I can use JSON Schema and Classes to do this but still didnt get through.
Could you please guide me?
Since you are dealing with JSON, you can simply load it into a JavaScript variable using require:
let data = require('./data.json');
You can then loop the variable for all entries tag
let fileData = require('./data.json');
let allEntries = [];
loadEntries(fileData);
function loadEntries(data) {
if(data.entries) {
for (let index = 0; index < data.entries.length; index++) {
const entry = data.entries[index];
// Do something with the entry
allEntries.push(entry);
loadEntries(entry);
}
}
}

How can I merge and match 2 separate objects?

What I want
I have 2 different Java-Script arrays/objects but with matching Ids. I want to merge them into a new object. So both the main object data and any matched elements from the secondary object are merged into a combined result.
What I tried
I tried using Object.assign() function but with no success.
Given Input
Example code, so I have 2 separate objects (main and lines):
let main = [
{
"Id": "1",
"Name": "Testing data"
}
]
let lines = [
{
"OtherId": "1",
"code": "AU-29830"
},
{
"OtherId": "1",
"code": "AU-29854-Single"
},
{
"OtherId": "1",
"code": "TV-BB21084623"
},
{
"OtherId": "2",
"code": "Don't Merge"
},
{
"OtherId": "3",
"code": "Don't Merge"
}
]
Expected Output
I want to merge those 2 arrays, so that the output should be a single array containing the merged main-object. This merged main-object should contain the original content of itself plus nested the filtered secondary array (only containing matching objects). The filtering was done using the id from the main array's object which has to match (the slightly deviating id) from each object of the secondary-array.
The resulting array should look like this:
let result = [
{
"Id": "1",
"Name": "Testing data",
"lines": [
{
"OtherId": "1",
"ProductCode": "AU-29830"
},
{
"OtherId": "1",
"ProductCode": "AU-29854-Single"
},
{
"OtherId": "1",
"ProductCode": "TV-BB21084623"
}
]
}
]
As your main is an array, I'm assuming you might end up with more than one main item in it. If so, here's one way to merge your line items onto each one:
const mergedMainItems =
main.map(mainItem=>({
...mainItem,
lines: lines.filter(line=>mainItem["Id"] === line["OtherId"])
}))
I think for this example this will work:
let result = [];
result.push({...main[0]}); //or even result.push(main[0])
result[0].lines = [];
for(let l in lines){
if(lines[l].code != "Don't Merge"){
result[0].lines.push({OtherId: lines[l].OtherId, ProductCode: lines[l].code})
}
}

Searching through JSON object

I am trying to search through a json object to select some values. For example I have a variable with the value 'product-2' and I want to look through the json object and return the attributes array of 'product-2'
{
"attributes": [
...
],
"portfolio": [
{
"conn": [
{
"product": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
},
{
"product": "product-2",
"description": "Description in here"
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
]
}
]
Could anyone tell me how I can achieve this? Thank you
EDIT:
As per Pramods request - I was working with the following js (although its really wrong I am sure)
$scope.productAttributes = [];
$scope.getProductDetails = function (product_id) {
console.log(product_id);
//search trough json
angular.forEach($scope.listOfProducts.product_id, function(value, key) {
// I was thinking I could loop through the json and when I find the matching product, then push its attributes into an array?
// if (key === enteredValue) {
// $scope.productAttributes.push({atribute: key});
// }
});
};
EDIT No.2
The JSON structure has changed
Use a filter to destructure the array.
In my example I use a filter within a Controller. This should probably be done in a service or a view. For brevity I used the filter in a controller.
The filter expression essentially says, return the first object in the array with a property 'product' that is 'product-2'
var app = angular.module('app', []).controller('MyController', MyController);
MyController.$inject = ['$filter'];
function MyController($filter) {
var data = [
{
"product": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
},
{
"product": "product-2",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
]
this.product = $filter('filter')(data, {product: "product-2"})[0];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController as vm">
Product-2: {{vm.product}}
</div>
</div>
Well, if you don't know how product-2 will be nested and you actually need to search for it, then you need to do a recursive search. A recursive function is a function that calls itself.
This means that you iterate over each of the keys, and if the key is an object, call the recursive function on that key as well, until the key you want is found.
Here is a similar question, with a few algorithms provided for doing recursive search on a JSON structure in JavaScript: traversing through JSON string to inner levels using recursive function
I think your JSON is wrong , So please correct it
Correct JSON
{
"attributes": [],
"portfolio": [
{
"conn": [
{
"product-1": {
"label": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
},
{
"product-2": {
"label": "product-2",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
}
]
}
]
}
And to parse above json and return product information following is the code
$(document).ready(function() {
$.each(dict['portfolio'][0], function(key, list){
$.each(list, function(index, value){
$.each(value, function(product, info){
if (product == "product-2"){
answer = {}
answer[product] = info;
return JSON.stringify(answer);
}
});
});
});
});
Fiddle link :-
http://fiddle.jshell.net/2t8uknkc/

How to create JSON using Javascript with sets of data?

I know that I can create this JSON:
[
{
"Title": "Something",
"Price": "234",
"Product_Type": "dsf sf"
},
{
"Title": "hskiuea",
"Price": "4234",
"Product_Type": "sdawer"
}
]
*It uses the values obtained from text inputs contained within an element with the class "newpappend" - As shown below
Using the following code which obtains values from my HTML:
var jsonObj = []; //declare array
$(".newpappened").each(function () {
var p_title = $(this).find('#p_title').val();
var p_price = $(this).find('#p_price').val();
var p_ptype = $(this).find('#p_ptype').val();
jsonObj.push({Title: p_title, Price: p_price, Product_Type: p_ptype});
$(this).remove();
});
But, my goal is to end up with the JSON structured like this:
{
"Product_List": {
"Product": [
{
"Title": "asdf",
"Price": "53",
"Product_Type": "Adfsdf"
},
{
"Title": "asgsd",
"Price": "123",
"Product_Type": "Ntohig"
}
]
}
}
Basically, I am struggling with the correct Javascript to use to reach my goal
You are really close. Start with what you have, and then later:
var output = {
"Product_List": {
"Product": jsonObj
}
}
// output is now what you are looking for.

Categories