Related
I have JSON format like this I not sure how do I create new array of objects from an different array of object
[
{
"description":"microsoftLocation",
"icon":"Marker",
"data_id":"123",
"reference":"_1_microsoftOffice",
"id":1,
"text":"microsoftOffice"
},
{
"description":"facebookOffice",
"icon":"Marker",
"data_id":"456",
"reference":"_2_facebookOffice",
"id":2,
"text":"_2_microsoftOffice"
},
]
I want the output to look something like this and not sure how to get the dynamic url as well
[
{
"url":"http://localhost:3000/layer?text=microsoftLocation&data_id=123",
"text":"microsoftLocation",
"active":true,
"icon":Marker
},
{
"url":"http://localhost:3000/layer?text=facebookOffice&data_id=123",
"text":"facebookOffice",
"active":true,
"icon":Marker
},
]
You can do it using a map like this:
const data = [{
"description": "microsoftLocation",
"icon": "Marker",
"data_id": "123",
"reference": "_1_microsoftOffice",
"id": 1,
"text": "microsoftOffice"
},
{
"description": "facebookOffice",
"icon": "Marker",
"data_id": "456",
"reference": "_2_facebookOffice",
"id": 2,
"text": "_2_microsoftOffice"
},
];
const newData = data.map(el => ({
url: `http://localhost:3000/layer?text=${el.description}&data_id=${el.data_id}`,
text: el.description,
active: true,
icon: el.icon
}));
console.log(newData);
Just use map method in order to map from the original object properties to the new ones.
const array = [
{
"description":"microsoftLocation",
"icon":"Marker",
"data_id":"123",
"reference":"_1_microsoftOffice",
"id":1,
"text":"microsoftOffice"
},
{
"description":"facebookOffice",
"icon":"Marker",
"data_id":"456",
"reference":"_2_facebookOffice",
"id":2,
"text":"_2_microsoftOffice"
},
];
console.log(array.map(obj => ({ icon: obj.icon, active: true, text: obj.description, url: `http://localhost:3000/layer?text=${obj.description}&data_id=${obj.data_id}`})))
I am really junior with JavaScript and json, so I have this JSON input, and I need to get all that information in the "properties" object to create a new JSON object with just that information.
I'm using a base code like this one, but this is just returning {}.
exports.step = function(input, fileInput) {
var alert = {
'Properties': input.alert.properties
}
return JSON.stringify(alert, undefined, 1);
};
Original JSON:
"value": {
"id": "12345",
"entity": {
"_integrationDefinitionId": "7a6764",
"_integrationName": "Apple Main",
"_beginOn": "2021-09-01T02:20:06.189Z",
"displayName": "apple-onev",
"_accountIdPartitioned": "12345|12",
"_class": [
"Deployment",
"Group"
],
"_version": 3,
"_integrationClass": [
"CiSSP",
"Infrastructure"
],
"_accountId": "123456",
"_id": "1e234567",
"_key": "arn:aws:autoscaling:us-west-2:83712398:autoScalingGroup:asd1238-20c8-41aa-bcec-12340912341:autoScalingGroupName/awseb-e-juancito-stack-AWSEBAutoScalingGroup-123456",
"_type": [
"aws_autoscaling_group"
],
"_deleted": false,
"_rawDataHashes": "1233456==",
"_integrationInstanceId": "54321",
"_integrationType": "aws",
"_source": "integration",
"_createdOn": "2021-07-19T23:19:19.758Z"
},
"properties": {
"webLink": "https://google.com",
"arn": "name",
"region": "us-west-2",
"name": "JonnyAndTheVibes",
"launchConfigurationName": "OtherName",
"minSize": 1,
"maxSize": 4,
"desiredCapacity": 1,
"defaultCooldown": 360,
"availabilityZones": "us-west-2a",
"LoadBalancerNames": "MoreInfo",
"healthCheckType": "EC2",
"healthCheckGracePeriod": 0,
"instanceIds": "InstanceName",
"subnetIds": "subnet",
"terminationPolicies": "Default",
"newInstancesProtectedFromScaleIn": false,
"serviceLinkedRoleARN": "aMoreInfo",
"tag.Name": "atag",
"tag.application": "othertag",
"tag.aws:cloudformation:logical-id": "moretagsp",
"tag.aws:cloudformation:stack-id": "taggigante",
"tag.aws:cloudformation:stack-name": "ydaleconlostags",
"tag.elasticbeanstalk:environment-id": "seguimosmetiendoletags",
"tag.elasticbeanstalk:environment-name": "tag",
"tag.env": "tag",
"tag.team": "tag",
"accountId": "tag",
"tag.AccountName": "tag",
"tag.Production": true,
"#tag.Production": ""
}
}
I'm sure that it will be a simple solution.
You appear to be trying to grab properties from the wrong object. It should be value not alert.
const json = '{"value":{"id":"12345","entity":{"_integrationDefinitionId":"7a6764","_integrationName":"Apple Main","_beginOn":"2021-09-01T02:20:06.189Z","displayName":"apple-onev","_accountIdPartitioned":"12345|12","_class":["Deployment","Group"],"_version":3,"_integrationClass":["CiSSP","Infrastructure"],"_accountId":"123456","_id":"1e234567","_key":"arn:aws:autoscaling:us-west-2:83712398:autoScalingGroup:asd1238-20c8-41aa-bcec-12340912341:autoScalingGroupName/awseb-e-juancito-stack-AWSEBAutoScalingGroup-123456","_type":["aws_autoscaling_group"],"_deleted":false,"_rawDataHashes":"1233456==","_integrationInstanceId":"54321","_integrationType":"aws","_source":"integration","_createdOn":"2021-07-19T23:19:19.758Z"},"properties":{"webLink":"https://google.com","arn":"name","region":"us-west-2","name":"JonnyAndTheVibes","launchConfigurationName":"OtherName","minSize":1,"maxSize":4,"desiredCapacity":1,"defaultCooldown":360,"availabilityZones":"us-west-2a","LoadBalancerNames":"MoreInfo","healthCheckType":"EC2","healthCheckGracePeriod":0,"instanceIds":"InstanceName","subnetIds":"subnet","terminationPolicies":"Default","newInstancesProtectedFromScaleIn":false,"serviceLinkedRoleARN":"aMoreInfo","tag.Name":"atag","tag.application":"othertag","tag.aws:cloudformation:logical-id":"moretagsp","tag.aws:cloudformation:stack-id":"taggigante","tag.aws:cloudformation:stack-name":"ydaleconlostags","tag.elasticbeanstalk:environment-id":"seguimosmetiendoletags","tag.elasticbeanstalk:environment-name":"tag","tag.env":"tag","tag.team":"tag","accountId":"tag","tag.AccountName":"tag","tag.Production":true,"#tag.Production":""}}}';
function getAlert(dsta) {
// Destructure the properties object from the
// data's value property
const { properties } = data.value;
// Create a new object with it
const alert = { properties };
// Return the string
return JSON.stringify(alert, null, 2);
};
// Parse the JSON
const data = JSON.parse(json);
// Call the function with the parsed data
const alert = getAlert(data);
console.log(alert);
Additional information
Destructuring assignment
use this function :
function assignJsons(...jsons) {
const convertToObject = jsons.map(json => {
return JSON.parse(json)
});
return JSON.stringify(Object.assign(...convertToObject))
}
//test
console.log(assignJsons(`{"name" : "alex", "family" : "mask"}`, `{"family" : "rejest"}`))
if you want a completely new object
var newJsonObject = JSON.parse('{ "properties":'
+ JSON.stringify (origJson.value.properties) + "}");
or
var newJsonObject={"properties":Object.assign ({}, origJson.value.properties)};
I am building a web-app and want to connect data from Quandl through its JSON API.
However, the JSON I get from quandl has the column names separate from the data itself, check below:
{
"datatable": {
"data": [
[
"AAPL",
"MRY",
"2020-12-31",
"2020-09-26",
"2020-09-26",
"2021-07-28",
-406000000,
323888000000,
325562500000
]
],
]
],
"columns": [
{
"name": "ticker",
"type": "String"
},
{
"name": "dimension",
"type": "String"
},
{
"name": "calendardate",
"type": "Date"
},
{
"name": "datekey",
"type": "Date"
},
{
"name": "reportperiod",
"type": "Date"
},
{
"name": "lastupdated",
"type": "Date"
},
{
"name": "accoci",
"type": "Integer"
},
{
"name": "assets",
"type": "Integer"
},
{
"name": "assetsavg",
"type": "Integer"
}
]
},
"meta": {
"next_cursor_id": null
}
}
When I use this data in Appsmith, it can not infer the column names. Is there a simple javascript code to combine the column names with the data? Thank you!
This is possible with a simple JS snippet, Now my code written is not that great but will work in this case (Can be optimised)
{{
function() {
let tableData = [];
_.map(_d.datatable.data, (v, i) => {
let set = {}
_.map(v, (x, k) => {
var obj = {[_d.datatable.columns[k].name]: x}
set = {...set, ...obj}
})
tableData.push(set)
})
}()
}}
In the above snippet _d is the data which you receive, We map the array value index with the given column index and create a new object out of it, Also since this is a multiline JS code, In Appsmith we need to write this inside an IIFE like above.
I have an array of timeseries objects that I need to filter in React.
Specifically, I need to return an array containing a filtered subset of the array of objects, based on the value of device_id being equal to e.g. 7F34B296.
The raw array looks as below:
[
{
"label": "time_stamp",
"data": [
"2019-04-17 21:01:25.673949957+02:00",
"2019-04-17 21:01:30.673949957+02:00",
"2019-04-17 21:01:35.673949957+02:00",
"2019-04-17 21:01:40.673949957+02:00",
"2019-04-17 21:01:45.673949957+02:00"
]
},
{
"label": "device_id",
"data": [
"7F34B296",
"7F34B296",
"7F34B296",
"AB22438D",
"AB22438D"
]
},
{
"label": "parameter_x",
"data": [
"929.1965116",
"927.5152582",
"928.7476077",
"1919.2691327",
"1918.7047619"
]
}
]
The intended output array (after filtering) looks as below:
[
{
"label": "time_stamp",
"data": [
"2019-04-17 21:01:25.673949957+02:00",
"2019-04-17 21:01:30.673949957+02:00",
"2019-04-17 21:01:35.673949957+02:00"
]
},
{
"label": "device_id",
"data": [
"7F34B296",
"7F34B296",
"7F34B296"
]
},
{
"label": "parameter_x",
"data": [
"929.1965116",
"927.5152582",
"928.7476077"
]
}
]
I tried using various methods, including below - but I seem unable to get the desired result. I think I'm missing the part on how to handle that the filtering of the entire array of objects should depend on the value of a subset of one of the objects.
const filters = [
{
predicateFn: data => data.data == "7F34B296"
}
];
function getFilteredPersons(filters) {
return datasets.filter(p => filters.every(filter => filter.predicateFn(p)));
}
console.log(getFilteredPersons(filters));
Maybe try to map your data to some kind of the structure f.e.:
const joinedData = []
data.map((element) =>
element.data.map((e, i) => joinedData[i] = { [element.label]: e, ...joinedData[i]}))
Then you will have transformed data in shape:
[
{
parameter_x: '929.1965116',
device_id: '7F34B296',
time_stamp: '2019-04-17 21:01:25.673949957+02:00'
},
{
parameter_x: '927.5152582',
device_id: '7F34B296',
time_stamp: '2019-04-17 21:01:30.673949957+02:00'
},
{
parameter_x: '928.7476077',
device_id: '7F34B296',
time_stamp: '2019-04-17 21:01:35.673949957+02:00'
},
{
parameter_x: '1919.2691327',
device_id: 'AB22438D',
time_stamp: '2019-04-17 21:01:40.673949957+02:00'
},
{
parameter_x: '1918.7047619',
device_id: 'AB22438D',
time_stamp: '2019-04-17 21:01:45.673949957+02:00'
}
]
which will be easier to filter
If your data object is always structured same way (3 elements each on same place), then you can do something like this:
const data = [
{
"label": "time_stamp",
"data": [
"2019-04-17 21:01:25.673949957+02:00",
"2019-04-17 21:01:30.673949957+02:00",
"2019-04-17 21:01:35.673949957+02:00",
"2019-04-17 21:01:40.673949957+02:00",
"2019-04-17 21:01:45.673949957+02:00"
]
},
{
"label": "7F34B296",
"data": [
"7F34B296",
"7F34B296",
"7F34B296",
"AB22438D",
"AB22438D"
]
},
{
"label": "parameter_x",
"data": [
"929.1965116",
"927.5152582",
"928.7476077",
"1919.2691327",
"1918.7047619"
]
}
]
const mainData = data[1];
const deviceId = mainData.label;
const indexes = mainData.data.filter((item) => item === deviceId).map((e, idx, array) => idx);
const result = data.map((value) => {
const filteredData = value.data.filter((item, idx) => {
return indexes.some((e => idx === e));
})
return {
...value,
data: filteredData
}
});
console.log(result)
Basically just find indexes of device_id in second element of array, and then extract values on those indexes of device_id, time_stamp and parameter_x data properties.
Although this might work, I'd suggest restructuring your data because this is quite complicated structure.
We can use forEach method with splice to get desired output.
let arr = [
{
"label": "time_stamp",
"data": [
"2019-04-17 21:01:25.673949957+02:00",
"2019-04-17 21:01:30.673949957+02:00",
"2019-04-17 21:01:35.673949957+02:00",
"2019-04-17 21:01:40.673949957+02:00",
"2019-04-17 21:01:45.673949957+02:00"
]
},
{
"label": "device_id",
"data": [
"7F34B296",
"7F34B296",
"7F34B296",
"AB22438D",
"AB22438D"
]
},
{
"label": "parameter_x",
"data": [
"929.1965116",
"927.5152582",
"928.7476077",
"1919.2691327",
"1918.7047619"
]
}
]
arr.forEach( (val, index) => val.data.splice(3) )
console.log(arr)
I have result json file with 10000 of lines. inside the one array object there are some unnecessary json object i need remove. I have tried so many ways but it's didn't work for me. herewith the piece line of json file
[
{
"product_id": "easybridge",
"errors": []
},
{
"product_id": "learningstudio",
"errors": []
},
{
"product_id": "pearsontestprep",
"errors": []
},
{
"product_id": "productization",
"errors": []
},
{
"product_id": "equella",
"errors": [
{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
"schema": {
"$id": "#/properties/test_ids/items",
],
"properties": {
"trend": {
"$id": "#/properties/test_ids/items/properties/trend",
"examples": [
true
]
},
"display": {
"$id": "#/properties/test_ids/items/properties/display",
"type": "boolean",
"examples": [
true
]
},
"test_id": {
"$id": "#/properties/test_ids/items/properties/test_id",
"type": "string",
},
"test_name": {
"$id": "#/properties/test_ids/items/properties/test_name",
"type": "string",
},
"maintenance": {
"$id": "#/properties/test_ids/items/properties/maintenance",
"type": "boolean",
]
},
"instance": {
"trend": false,
"display": false,
"test_id": "8597ae3c-e2a9-45c7-b279-bde1710681be",
"test_name": "Equella Pearsonresearch Ping Test",
"nrAlertStatus": "enabled",
"test_locations": [
{
"alert_state": false,
"location_name": "AWS_US_WEST_2",
"location_label": "Portland, OR, USA",
"included_to_health": false
}
],
"included_to_health": false,
"critical_alert_threshold": 60
},
"name": "required",
"argument": "maintenance",
"stack": "instance.test_ids[1] requires property \"maintenance\""
{
"product_id": "easybridge",
"errors": []
},
I just need only
{
"product_id": "equella",
"errors": [
{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
}
},
if the errors json array is not empty. i don't need even this json how can i remove "schema" json object and other unnecessary json object and arrays specially "schema" json object using java script or java. please help
Loop through the array, look at each object, and create a new array by copying over the data you need.
For instance, I'm taking it you don't care about an object if its array of errors is empty, and that you don't care about the schema ever:
let newJSON = [];
//Assume the json variable is the parsed JSON file you posted.
for (let element of json) {
//Must have at least one error
if (element.errors.length > 0) {
//Create a new object
let newObj = {
"product_id" : element.product_id,
"errors" : []
};
//Add each errror
for (let error of element.errors) {
//Only copy across what we need
newObj.errors.push({
"property" : error.property,
"message" : error.message
});
}
//Add object to our new array of JSON
newJSON.push(newObj);
}
}
//newJSON is your processed JSON output
The easiest solution can be:
const records = [{
"product_id": "learningstudio",
"errors": []
},
{
"product_id": "pearsontestprep",
"errors": []
},
{
"product_id": "equella",
"errors": [{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
"schema": {
"$id": "#/properties/test_ids/items",
}
}]
}];
const filteredRecords = records.map((record) => {
record.errors = record.errors.map((error) => {
return {property: error. property, message: error.message};
});
return record;
});
console.log(filteredRecords);
You can use map and destructuring assignment to capture only desired properties
let json = [{"product_id": "equella", "errors": [{"property": "instance.test_ids[1]","message": "requires property \"maintenance\"",'xyz': 'not needed','useless': 'not needed',},{'xyz': 'not needed',}]},]
let op = json.map(({product_id,errors}) =>{
let { property, message } = errors[0]
return { product_id, errors: {property,message}}
})
console.log(op)