I am very new to development and I am trying to figure out the best way to convert a current export tool I wrote that exports a JSON object to now include a JSON object that has an array of objects on the inside. What I am referring to is the array of objects on profile: I tried using .push() to put the objects into the array but I am lost.
Ideal JSON object
{
"id": "220a5f58-480e-45c3-8252-b3712d9e6c32",
"name": "hello",
"profile": [
{
"fullName": "test",
"displayName": "test",
"number": "Unknown",
"attributes": {
"identifier": true,
"categorical": false,
"quantized": false,
"relational": false,
"ordinal": false
}
},
{
"fullName": "test",
"displayName": "test",
"number": "Unknown",
"attributes": {
"identifier": true,
"categorical": false,
"quantized": false,
"relational": false,
"ordinal": false
}
}
],
"test": 12
}
JS Code
// object.profile is a JSON object
export.profile = [];
angular.forEach(object.profile, function (value, key) {
//export.profile[key] = {};
export.push(profile[key] );
export.profile[key].attributes = {};
export.profile[key].fullName = (value['original-name']);
export.profile[key].displayName = (value['display-name']);
export.profile[key].interpretation = (value['interpretation']['iName']);
export.profile[key].mainType = (value['main-type']);
Related
I have json data like this.
var obj= {
"id": "6",
"name": "parent",
"path": "/",
"category": "folder",
"fid":"6"
"children": [
{
//some values
},
{
//some other values
}
]
}
how to iterate and push it into an new array.
type declaration
getEntry: Array<Object> = []
pushing into an array method
get addedEntry() {
let files = []
this.getEntry = files.push(this.obj)
}
But, i am getting type error. How to push this object into an array or make it array.?
The push method returns a Number representing the new value of the array. That's why you are getting a TypeError (you are assigning a Number to an Array of Objects).
You should do the following instead.
get addedEntry() {
let files = []
files.push(this.obj)
this.getEntry = files
}
Here's the docs entry for the push method in JavaScript.
I'm trying to loop through a JSON and sort it by the date so I can see the latest date to the oldest date, and then write it to the file.
Here is my code
var reader = JSON.parse(fs.readFileSync('txt.json', 'utf8'));
function sortByDate(a, b) {
return new Date(a.lastUpdated).toJSON() - new Date(b.lastUpdated).toJSON();
}
reader.sort(sortByDate)
JSON Data Example
{
"Data": {
"Contents": [
{
"Key": [
"HelloTest"
],
"lastUpdated": [
"2019-10-25T10:30:50.558Z"
]
},
{
"Key": [
"TestHello"
],
"lastUpdated": [
"2019-03-26T10:30:50.558Z"
]
}
]
}
}
Here are a couple of errors I found in your code:
Your function name has a typo, it should be sortByDate and not sortbyDate.
You need top sort the inner json.Data.Contents array, not the outer json object.
You need to reference the first element of your lastUpdated arrays using lastUpdated[0].
Finally, you do not need to call toJSON() on the date objects in your sorting function, simply convert to date and return the difference.
Also your inner data fields are arrays, which seems strange for a Key and a lastUpdated value.
If you keep your fields as arrays, here is a working example showing how to sort the inner Data.Contents array by date:
const jsonString = `{
"Data": {
"Contents": [{
"Key": ["HelloTest"],
"lastUpdated": ["2019-10-25T10:30:50.558Z"]
}, {
"Key": ["TestHello"],
"lastUpdated": ["2019-03-26T10:30:50.558Z"]
}]
}
}`;
function sortByDate(a, b) {
return new Date(a.lastUpdated[0]) - new Date(b.lastUpdated[0]);
}
const json = JSON.parse(jsonString);
const defaultValue = { Data: { Contents: [] } };
const sortedContents = [...(json || defaultValue).Data.Contents].sort(sortByDate);
const output = { ...json, Data: { Contents: sortedContents } };
console.log(output);
If you change your fields to scalars, which I suggest, here is another example:
const jsonString = `{
"Data": {
"Contents": [{
"Key": "HelloTest",
"lastUpdated": "2019-10-25T10:30:50.558Z"
}, {
"Key": "TestHello",
"lastUpdated": "2019-03-26T10:30:50.558Z"
}]
}
}`;
function sortByDate(a, b) {
return new Date(a.lastUpdated) - new Date(b.lastUpdated);
}
const json = JSON.parse(jsonString);
const defaultValue = { Data: { Contents: [] } };
const sortedContents = [...(json || defaultValue).Data.Contents].sort(sortByDate);
const output = { ...json, Data: { Contents: sortedContents } };
console.log(output);
It looks like you're reading contents from a file, then needs to sort it by date, and then finally write it to a new file. If that is what you're going for, the following should help:
const fs = require('fs');
const path = require('path');
// JSON files can be requied in as objects without parsing
// `arrayOfStuff` will be the var name for `Contents`
const { Data: { Contents: arrayOfStuff } } = require('./data.json');
function sortByDate(el1, el2) {
// access the date from the object and turn into date object
let date1 = new Date(el1.lastUpdated[0]);
let date2 = new Date(el2.lastUpdated[0]);
// compare date objects in revers order to get newest to oldest
return (date2 - date1);
}
// sort `Contents` from the `Data` object and turn into JSON
const sortedContent = arrayOfStuff.sort(sortByDate);
const newDataObj = JSON.stringify({ Data: { Content: sortedContent }}, null, 2);
// create the fully qualified file path with `sortedByDate.json` as the file name
const filePath = path.resolve('./', 'sortedByDate.json');
// write to new file
fs.writeFile(filePath, newDataObj, (err) => {
if(err) {
console.log('Made an oopsie:', err);
}
console.log(`Success!, new JSON file located at: ${filePath}`);
}); // write to file
Hi I have have a given array of JSON object in a file:
file.json:
[
{
"id": "xccdf_saphana.content_profile_test1",
"info": {
"applicable_platforms": ["SUSE", "RHEL", "SUSE FOR SAP APP"],
"applicable_workloads": "SalesPromo",
"applicable_compliance": "CIS",
"type":"System"
}
},
{
"id": "xccdf_saphana.content_profile_test2",
"info": {
"applicable_workloads": "SalesPromo",
"applicable_compliance": "CIS",
"type":"System"
}
}
]
Below is the way I am reading it.
var obj = JSON.parse(fs.readFileSync(file.json, 'utf8')); // read the file
myID = "xccdf_saphana.content_profile_test2";
var myInfo = getInfobyID(myID);
function getInfobyID(myID) {
// Got messed up, tried changing JSON structure multiple time, so that I can easily parse it.
for(var i=0; i < obj.length; ++i) {
if(obj[i].id == myID)
return obj[i].info;
}
}
Is their any way I can optimize it, as I will be recursively searching for multiple myID later.
Turn your json into an object rather than an array. Then you can make quick lookups.
let hash = obj.reduce((agg, e) => {
agg[e.id] = e;
return agg;
}, {});
let value = hash["xccdf_saphana.content_profile_test2"].info;
The naming 'obj' is a bit confusing here since it is actually an array of objects (from the JSON file).
Try something like:
var myArrOfObj = JSON.parse(fs.readFileSync(file.json, 'utf8'));
var myID = "xccdf_saphana.content_profile_test2";
var myInfo = getInfobyID(myID);
function getInfobyID(myID){
var matchingObj = myArrOfObj.find((obj) => obj.id === myID);
// Fallback to empty string since there might be no match.
return (matchingObj) ? matchingObj.info : '';
}
You can use Array.reduce to convert your array into an object with key as id and value as info.
Now you can just return the object[id] and get the info without iterating everytime.
var json = [{
"id": "xccdf_saphana.content_profile_test1",
"info": {
"applicable_platforms": ["SUSE", "RHEL", "SUSE FOR SAP APP"],
"applicable_workloads": "SalesPromo",
"applicable_compliance": "CIS",
"type": "System"
}
},
{
"id": "xccdf_saphana.content_profile_test2",
"info": {
"applicable_workloads": "SalesPromo",
"applicable_compliance": "CIS",
"type": "System"
}
}
];
var data = json.reduce((acc, curr) => {
acc[curr.id] = curr.info;
return acc;
}, {});
function getInfobyID(data, id) {
return data[id];
}
console.log(getInfobyID(data, "xccdf_saphana.content_profile_test2"));
Based on this requirement:
Is their any way I can optimize it...
You may want to store the ID value as the key of a map, and any info related to it as the value. This way, whenever you are searching, if you already have the ID yo can access the data for that ID in constant time, or O(1), as opposed to linear time, or O(n).
This is the only way to speed up your search without more complex data structures, but it comes with one caveat which is that you no longer have a list. You will be using a map.
Change this:
[
{
"id": "xccdf_saphana.content_profile_test1",
"info": {
"applicable_platforms": ["SUSE","RHEL","SUSE FOR SAP APP"],
"applicable_workloads": "SalesPromo",
"applicable_compliance": "CIS",
"type":"System" }
},
{
"id": "xccdf_saphana.content_profile_test2",
"info": {
"applicable_workloads": "SalesPromo",
"applicable_compliance": "CIS",
"type":"System" }
}
]
To this:
{
"xccdf_saphana.content_profile_test1": {
"applicable_platforms": ["SUSE","RHEL","SUSE FOR SAP APP"],
"applicable_workloads": "SalesPromo",
"applicable_compliance": "CIS",
"type":"System"
},
"xccdf_saphana.content_profile_test2": {
"applicable_workloads": "SalesPromo",
"applicable_compliance": "CIS",
"type":"System"
}
}
Now you don't need any loops. You just have one object, with each member of the object representing a different item.
In your code, you can simply do obj[myId] and you will either get undefined if it doesn't exist, or you will get an object of the matching result.
This is the fastest a search could possibly be, but again it requires a map-like data structure and not a list.
If you absolutely must use a list, the only real optimization to be made is as follows:
Cache your list length, so you do not have to calculate it on each iteration of the loop
Your new getInfobyID could look like this:
function getInfobyID(myID){
var len = obj.length;
for (var i=0; i < len; ++i){
if( obj[i].id == myID)
return obj[i].info;
}
}
I'm trying to remove an object from Json Object it works..but it replace it with null..i dont know why, how can i remove the null value from the json..heres the function :
company.deleteExternalLinkFromGrid = function (row, matricule) {
// console.log('Inside of deleteModal, code = ' + code);
//$scope.sitting= {};
console.log(matricule);
//console.log(JSON.stringify(linkJsonObj));
delete linkJsonObj[matricule];
console.log(JSON.stringify(linkJsonObj));
};
heres the object:
[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null]
You can use filter(), x will be without null's.
function test()
{
var x =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null].filter(isNotNull);
alert(JSON.stringify(x));
}
function isNotNull(value) {
return value != null;
}
fiddle
There are multiple ways to delete an object from an array of objects in JavaScript. You don't need AngularJS for that, you can use VanillaJS.
If you just want the nulls filtered you can use
var yourArray =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null];
yourArray = yourArray.filter(function(elt){
return elt != null;
});
But this loses the original reference to your object.
If you want to keep the reference, Use array.splice().
yourArray.forEach(function(){
yourArray.splice(yourArray.indexOf(null),1);
});
now you will have null less array in yourArray. This actually deletes an object from an array without changing the reference,
delete will replaced the object with undefined
You can filter the array to remove them using Array#filter()
var array = [{
"name": "xxx",
"link": "www.ddd.com",
"id": 0,
"$$hashKey": "uiGid-001Z"
}, {
"name": "xx",
"link": "www.dddcom",
"id": 1,
"$$hashey": "uiGrid-0029"
}, {
"name": "xxx",
"link": "www.ddd.com",
"id": 2
}];
delete array[1];
array = array.filter(a=>a);
console.log(JSON.stringify(array));
My data consists of an object that has nested objects with each key being the id, I want to parse the collection response.payload but when I do the collection is returned as 1 object containing the nested objects. Can anyone advise on how I can make each nested object a model?
JS
var data = {
"payload": {
"020": {
"sessions": ["SES1", "SES2", "SES3", "SES4"],
"account": [],
"tag": []
},
"650": {
"sessions": ["SES11", "SES12", "SES13"],
"account": ["ACCT1", "ACC2", "ACC3"],
"tag": []
},
"880": {
"sessions": ["SES900", "SES901"],
"account": ["abc", "DEF"],
"tag": ["TAG5", "TAG53"]
}
}
};
var SearchCollection = Backbone.Collection.extend({
parse: function(response) {
console.log(response.payload);
return response.payload;
}
});
var searchCollection = new SearchCollection(data, {parse: true});
console.log(searchCollection.toJSON());
Do I need to loop the response in parse and create model with a key id instead or create a model and do some parsing there?
JS Fiddle http://jsfiddle.net/t6w0bcu6/22/
I would "loop the response in parse and create model with a key id". Here's one way to do it.
var SearchCollection = Backbone.Collection.extend({
parse: function(response) {
var models = [];
_.each(response.payload,(value, key)=>{
value.id = key;
models.push(new Backbone.Model(value))
})
return models;
}
});
http://jsfiddle.net/t6w0bcu6/23/