Push an item into a JSON Array - javascript

I have a JavaScript function that makes an ajax call to an API, and gets a JSON array.
Here is a sample of an array that I get:
[
{
"ErrorType": "Errors",
"Explanations": [
{
"Explanation": "Price Missing",
"Locations": [
25,
45
]
},
{
"Explanation": "Unit of measurement not valid",
"Locations": [
25,
301,
302
]
}
]
},
{
"ErrorType": "Warnings",
"Explanations": [
{
Blablabla,
Ithinkthere's already much here
}
]
}
]
I put it into a JavaScript array:
$scope.CorrectionDatas = ResponseFromApi;
So, for each ErrorType, I have some "explanations". I would like to add another property, in order to have something like this :
[
{
"ErrorType": "Errors",
"Explanations": [
{
"Explanation": "Price Missing",
"Locations": [
25,
45
]
},
{
"Explanation": "Unit of measurement not valid",
"Locations": [
25,
301,
302
]
}
],
"show": true
},
{
"ErrorType": "Warnings",
"Explanations": [
{
Blablabla,
Ithinkthere's already much here
}
],
"show":true
}
]
I though that I could do it only by doing it like that:
$scope.CorrectionDatas.forEach(function (error) {
error.push({ show: true });
});
But my debugger gives me an error:
Error: error.push is not a function
$scope.getErrors/</<#http://localhost:1771/dependencies/local/js/Correction/CorrectionCtrl.js:26

Each error is an object so it don't have push, the code should be:
$scope.CorrectionDatas.forEach(function(error) {
error.show = true;
});

Try this way:
$scope.CorrectionDatas.forEach(function (error){
error["show"] = true;
});

I believe that the problem you're encountering is that error is not an array, it is an object. This can be confirmed by logging the output of typeof error. If this is the case, you must explicitly define the show property of the object, as so:
$scope.CorrectionDatas.forEach(function (error){
error['show'] = true; // alternatively, error.show = true;
});

Related

Remove JSON row columns without looping

I have an API that returns JSON data. But now I want to remove some of the data without looping through the entire object.
The sample JSON data is:
[
{
"cost":"KES 0.8000",
"messageId":"ATXid_0fae395279b54d51519de5581230a7e8",
"messageParts":1,
"number":"+2547112xxxxxx",
"status":"Success",
"statusCode":101
},
{
"cost":"KES 0.8000",
"messageId":"ATXid_19a0a09efcf39e87245a57f6403631d5",
"messageParts":1,
"number":"+2547112xxxxxx",
"status":"Success",
"statusCode":101
},
{
"cost":"0",
"messageId":"None",
"number":"+25470000000000",
"status":"InvalidPhoneNumber",
"statusCode":403
}
]
I want to extract only data like:
[
{
"number":"+2547112xxxxxx",
"status":"Success"
},
{
"number":"+2547112xxxxxx",
"status":"Success"
},
{
"number":"+25470000000000",
"status":"InvalidPhoneNumber"
}
]
I am working using Node.js with express framework.
In simple ways, using the .map() function, you can do something like this:
console.log(arr.map(({number, status}) => ({
number,
status
})));
Full Snippet
const arr = [{
"cost": "KES 0.8000",
"messageId": "ATXid_0fae395279b54d51519de5581230a7e8",
"messageParts": 1,
"number": "+2547112xxxxxx",
"status": "Success",
"statusCode": 101
},
{
"cost": "KES 0.8000",
"messageId": "ATXid_19a0a09efcf39e87245a57f6403631d5",
"messageParts": 1,
"number": "+2547112xxxxxx",
"status": "Success",
"statusCode": 101
},
{
"cost": "0",
"messageId": "None",
"number": "+25470000000000",
"status": "InvalidPhoneNumber",
"statusCode": 403
}
];
console.log(arr.map(({number, status}) => ({
number,
status
})));

How to make vuex getter from data from google api docs?

I'm trying to make getter in vuex store with flat data from google dosc api. All what I need is to take textRun content and keep this in array (because there will be few messages). Now I hardcoded this response in state like:
state: {
googleResponse: [
{
"body": {
"content": [
{
"endIndex": 75,
"paragraph": {
"elements": [
{
"endIndex": 75,
"startIndex": 1,
"textRun": {
"content": "This is an ordinary paragraph. It is the first paragraph of the document",
"textStyle": {}
}
}
],
"paragraphStyle": {
"direction": "LEFT_TO_RIGHT",
"namedStyleType": "NORMAL_TEXT"
}
},
"startIndex": 1
},
{
"endIndex": 102,
"paragraph": {
"elements": [
{
"endIndex": 102,
"startIndex": 75,
"textRun": {
"content": "Here's a level one heading",
"textStyle": {}
}
}
],
"paragraphStyle": {
"direction": "LEFT_TO_RIGHT",
"headingId": "h.o1fkftgl5zwf",
"namedStyleType": "HEADING_1"
}
},
"startIndex": 75
},
]
}
}
],
}
and after that I make a getter message and used map from lodash:
message: (state) => {
let message = '';
map(state.googleResponse, (element) => ({
content: map(element.body.content, (content) => {
map(content.paragraph.elements, (obj) => {
message += get(obj, 'textRun', '')
})
})
}))
}
But when I'm checking message in vuex it says is undefined... I want to have array with textRun objects. Where might be the problem ?
i am wondering whether you can get the message keep in Array by this way?
you can write like this may your want
let messageArray = state.googleResponse.map(
item => item.body.content.map(
itemCotent => itemCotent.paragraph.elements.map(
itemElements => itemElements.textRun.content)))
You need to return themessage variable in your getter.

I need remove unnecessary json objects form my result json file using javascript

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)

No index exists while trying to sort using an indexed field (Mango Queries)

I'm not sure how to figure out how to sort my documents using a Mango query. Any help would be greatly appreciated:
I do the following find query and get the following error:
return db.find({ sort: ['timestamp'], selector: {$and: [{type:"revision"},{doc_id: doc_id}] } })
Note, if I do the following I also get the same error:
return db.find({ sort: ['timestamp'], selector: {$and: [{type:"revision"}] } })
{
error: 'no_usable_index',
reason: 'No index exists for this sort, try indexing by the sort fields.',
name: 'no_usable_index',
status: 400,
message: 'No index exists for this sort, try indexing by the sort fields.'
}
I created a filter like so:
db.createIndex({
index: {fields: ['type', 'timestamp']}
})
This is what pops up in my design documents:
{
"_id": "_design/b661014513bf0c13270a9033d6d1c1853a8b5dbf",
"_rev": "1-1d871456b0a78952845705f4e8dd2c26",
"language": "query",
"views": {
"b661014513bf0c13270a9033d6d1c1853a8b5dbf": {
"map": {
"fields": {
"type": "asc",
"timestamp": "asc"
},
"partial_filter_selector": {}
},
"reduce": "_count",
"options": {
"def": {
"fields": [
"type",
"timestamp"
]
}
}
}
}
}

How to find the value of an array attribute in javascript

I have the following script that outputs a json formatted object:
function test() {
autoscaling.describeAutoScalingGroups(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(JSON.stringify(data)); // successful response
});
}
test();
This outputs the following json:
{
"ResponseMetadata": {
"RequestId": "##################"
},
"AutoScalingGroups": [
{
"AutoScalingGroupName": "################",
"AutoScalingGroupARN": "arn:aws:autoscaling:eu-west-1:#########:autoScalingGroup:###########",
"LaunchConfigurationName": "######-LC-###########",
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"DefaultCooldown": 300,
"AvailabilityZones": [
"eu-west-1b",
"eu-west-1c",
"eu-west-1a"
],
"LoadBalancerNames": [
"#########-ELB-###########"
],
"TargetGroupARNs": [
],
"HealthCheckType": "ELB",
"HealthCheckGracePeriod": 300,
"Instances": [
],
"CreatedTime": "2017-11-08T18:22:05.093Z",
"SuspendedProcesses": [
{
"ProcessName": "Terminate",
"SuspensionReason": "User suspended at 2017-11-08T18:22:14Z"
}
],
"VPCZoneIdentifier": "subnet-######,subnet-#######,subnet-#######",
"EnabledMetrics": [
],
"Tags": [
{
"ResourceId": "#######-ASG-##########",
"ResourceType": "auto-scaling-group",
"Key": "aws:cloudformation:logical-id",
"Value": "ASG",
"PropagateAtLaunch": true
},
{
"ResourceId": "#######-ASG-#########",
"ResourceType": "auto-scaling-group",
"Key": "aws:cloudformation:stack-id",
"Value": "arn:aws:cloudformation:eu-west-1:########:stack/##############",
"PropagateAtLaunch": true
},
{
"ResourceId": "################",
"ResourceType": "auto-scaling-group",
"Key": "aws:cloudformation:stack-name",
"Value": "#######",
"PropagateAtLaunch": true
}
],
"TerminationPolicies": [
"Default"
],
"NewInstancesProtectedFromScaleIn": false
}
]
}
I need to get the value of "SuspendedProcesses":[{"ProcessName": (see above)
Then if the value of "ProcessName" == "Terminate" (as it is above) do this else do this.
I know how to construct the if else syntax but how do I establish the value of "ProcessName" from the JSON output beforehand?
I also know how to manipulate an array created in a script but I'm having difficulty here because the json object is being created by the test() function so the normal rules don't seem to apply.
Any help would be appreciated.
Thanks
First, replace your console.log() calls with return statements. Then you can just do
var json = test();
var processes = json["AutoScalingGroups"][0]["Suspended Processes"]
updated code:
function test() {
autoscaling.describeAutoScalingGroups(params, function(err, data) {
if (err) {
return [err, err.stack]; // an error occurred
} else {
var json = JSON.stringify(data); // successful response
return json["AutoScalingGroups"][0]["Suspended Processes"];
}
});
}
var processes = test()
console.log(processes);
thanks #RobbieMilejczak, problem resolved:
First, replace your console.log() calls with return statements. Then you can just do
var json = test();
var processes = json["AutoScalingGroups"][0]["Suspended Processes"]
updated code:
function test() {
autoscaling.describeAutoScalingGroups(params, function(err, data) {
if (err) {
return [err, err.stack]; // an error occurred
} else {
var json = JSON.stringify(data); // successful response
return json["AutoScalingGroups"][0]["Suspended Processes"];
}
});
}
var processes = test()
console.log(processes);

Categories

Resources