How to combine two JSON objects into an array - javascript

I have two JSON files - one pertaining to English Premier League data of 2015-16 and other of 2016-17. The JSON data in each file is as follows (extract only):
{
"name": "English Premier League 2015/16",
"rounds": [
{
"name": "Matchday 1",
"matches": [
{
"date": "2015-08-08",
"team1": {
"key": "manutd",
"name": "Manchester United",
"code": "MUN"
},
"team2": {
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
},
"score1": 1,
"score2": 0
},
and so on... lot of name, matches like this in the rounds array.
The data of 2016-17 is similar to above:
{
"name": "English Premier League 2016/17",
"rounds": [
{
"name": "Matchday 1",
"matches": [
{
"date": "2016-08-13",
"team1": {
"key": "hull",
"name": "Hull City",
"code": "HUL"
},
"team2": {
"key": "leicester",
"name": "Leicester City",
"code": "LEI"
},
"score1": 2,
"score2": 1
},
and so on... lot of name, matches like this in the rounds array.
These two are in two separate json files. I am developing an application in Angular 2 and have used a data service to get this data. That part was successful. However I need to use ngFor for creating rows in table and for that I require this data to be iterable like an array.
I have tried to convert these two json objects into an array but could not succeed.
1 I have initialised an empty array and tried to do array.push for each object. That did not work
arr=[];
if(this.data1516!=null && this.data1516!=undefined) {arr.push(this.data1516);}
if(this.data1617!=null && this.data1617!=undefined) {arr.push(this.data1617);}
2 I tried Object. assign -
this.obj=Object.assign({},this.data1516,this.data1617);
and then tried converting the object into array, even that did not work
All I want the final json single file to be an array of those two objects, like this:
[ {obj1} , {obj2} ]

There was a extra ] inside arr.push
This should work :
arr=[];
if(this.data1516!=null && this.data1516!=undefined) {
arr.push(this.data1516);
}
if(this.data1617!=null && this.data1617!=undefined) {
arr.push(this.data1617);
}
OR Shorter version (ES6)
arr = [ ...this.data1516 , ...this.data1617 ];

Related

JSON weird format access data

This is a JSON snip that is created in WooCommerce by a plugin that adds some metadata. I cannot change the formatting of this JSON because it is generated by a plugin. The problem is that the keys and the values are added in a weird way. I am iterating through the line_items and statically referencing this data which I don't want to do, I would like to know if there is a smart way to reference for example:
"key": "_cpo_product_id",
"value": "3572",
if this was formatted correctly it would be: "_cpo_product_id": "3572" and not have "value" as a key, and it would be accessed by: foo.line_items[i]._cpo_product_id
but with this configuration I am a bit lost, I am sure there is an easy way to find the value for a specific key. I am doing this on Google app scripts, but a solution in JavaScript should suffice.
JSON snip:
"line_items": [
{
"id": 749,
"name": "Dune",
"product_id": 3572,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "149.54",
"subtotal_tax": "31.40",
"total": "149.54",
"total_tax": "31.40",
"taxes": [
{
"id": 24,
"total": "31.403148",
"subtotal": "31.403148"
}
],
"meta_data": [
{
"id": 11919,
"key": "_cpo_product_id",
"value": "3572",
"display_key": "_cpo_product_id",
"display_value": "3572"
},
{
"id": 11920,
"key": "_add-to-cart",
"value": "3572",
"display_key": "_add-to-cart",
"display_value": "3572"
},

Remove special characters from a specific JSON object in JSON payload

I have a large JSON payload and I want to format, the specific object of the payload using JS.
I want flightdetails array object to edit and remove the special characters from it. How can I achieve this?
I have been working on this using XSLT for the past 2 days, and I went nowhere hence I decided to remove it using JS.
Example of the array(there can be more than 30 records inside the flightdetails)
"flightdetails": [
{
"id": XF-2092,
"trips": 2,
"categories": {
"flights": [
"\"return\",\"oneway\""
]
},
"id": XF-2093,
"trips": 1,
"categories": {
"flights": [
"\"return\""
]
}
}
]
Expected Output
"flightdetails": [
{
"id": XF-2092,
"trips": 2,
"categories": {
"flights": [
"return","oneway"
]
},
"id": XF-2093,
"trips": 1,
"categories": {
"flights": [
"return"
]
}
}
]
The flightdetails object inside the //destinations/flightdetails path

ExtJS data model unknown amount of fields

I have a data model that attempts to map all the incoming data, however I have to leave the data generic so i can add any number of meta data tags to my project. How can I either map these data fields to the Model or access these items in the array when applying grid filters.
{
"Link": "link.com",
"Title": "project",
"Description": "descript",
"State": "TN",
"Metadata": [
{
"Name": "County",
"Value": "32"
},
{
"Name": "Info",
"Value": "info"
},
{
"Name": "State",
"Value": "TN"
}
],
"XMin": "-1",
"XMax": "-1",
"YMin": "1",
"YMax": "1"
}
I think this is what you are looking for https://docs.sencha.com/extjs/4.2.1/#!/api/Ext.data.association.HasMany
There is also nice explanation about filtering on that page

How do I list fields in object inside array in MongoDB?

I'm working with the structure below for a multilanguage site. For this I'll be doing a tool to add/edit the needed words in the different languages that'll be available.
What I want to do is use a MongoDB (or Mongoose) query on my NodeJS/Express backend to get the keys for a specific language-
{
"languages": [
{
"_id": "5d4ee75c1c9d4400007e9bd8",
"code": "en",
"texts": [
{
"key": "language",
"word": "English"
},
{
"key": "title",
"word": "Colorblindness"
},
{
"key": "login",
"word": "Login"
}
]
},
{
"_id": "5d4ee8631c9d4400007e9bd9",
"code": "es",
"texts": [
{
"key": "language",
"word": "EspaƱol"
},
{
"key": "title",
"word": "Daltonismo"
},
{
"key": "account",
"word": "Cuenta"
},
{
"key": "exit",
"word": "Salir"
}
]
},
{ ... }
]
}
For example, if I query on "en" (English language), I'd expect the result to be something like
["language", "title", "login"]
, but if I query on "es" (Spanish language), the result should be
["language", "title", "account", "exit"]
Schema.findOne({code: "en"},(err,res)=>{
if (res) console.log(res.texts);
});
It's mongoose, it won't work with it's current but you need to edit it depending on your code starting by schema name.
Assuming every code has it's own fields, you should change "en" to "es".
For your query, assuming languages.code has unique values :
db.yourCollectionName.aggregate([
{$match:{'languages.code': "es"}},
{$unwind:'$languages'},
{$match:{'languages.code': "es"}},
{$project:{keys:'$languages.texts.key'}}
])
Assuming your collection is a large dataset then adding $match as first stage would filter documents where at-least one element of languages.code has value 'es'.

Working With Dynamic Multidimensional key-value pairs in JSON

Having a thorny problem and only see similar but also simpler solutions on SO.
Is is possible to generate a dynamic key AND dynamic values using JS/JSON?
For instance, let's say I have JSON like this:
{
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
I need to go into the fields and for each field (products, wines, fruits) see if a given service is contained within so that I can go back and generate a product or wine or fruit for each service that requires it. But I don't want to repeat the services names more than once. The resulting JSON should look something like this:
{"svc1":["Products"], "svc2":["Products"], "svc3":["Products"], "svc4":["Fruits", "Wines"]}
The hope would be that to generate a dynamic list in Angular I can just turn and loop back through this JSON, pulling out the values for each product, fruit, wine, whatever.
I've been trying a lot of nested for loops and the like but whenever I get more than one layer down the dynamism seems to stop. I'm guessing that for this to work I need to move between JS Objects and JSON?
Right now I'm trying something like this, which isn't quite working, stringify or no. And maybe I'm flip-flopping too much between JSON and JS Objects:
var outObj = [];
var fieldItems;
$.each(jsonObj.custom.fields, function(key, item) {
fieldItems = item;
fieldItems.name = item.name;
$.each(fieldItems.services, function(key, item) {
var serviceName = item;
//check to see if the serviceName already exists
if (outObj.indexOf(serviceName) > -1) {
outObj.serviceName.push(fieldItems.name);
} else {
outObj.push(serviceName);
}
});
});
JSON.stringify(outObj);
console.log("outObj " + outObj);
I get "can't read property 'push' of undefined" errors and the like. Seems this should be possible from a single nested loop, but maybe I need to just do two passes? Any other suggestions?
To me it sounds like overcomplicated solution. You can use basic array methods of javascript to filter out required structure. I am not sure what profiling_value in the presented snippet, so I started from the object structure in OP
var desiredResult = jsonObj.custom.services.reduce(function(result, service){
result[service.name] = jsonObj.custom.fields.filter(function(field){
return field.services.indexOf(service.name) >= 0;
}).map(function(field){ return field.name; });
return result;
}, {});
This gives the expected result for mentioned object.
reduce is required to iterate over all services and accumulate result in one object. Then for each service fields are iterated to filter out only those that contain link to this service. And finally list of filtered fields is transformed (map) into list of strings - their names - and inserted into accumulator

Categories

Resources