Remove JSON row columns without looping - javascript

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
})));

Related

calling firebase inside an forEach makes the iteration not work

Goal:
Im trying to make an array of objetcs including 3 informations: id, title and imageUri. But when i try to get the imageUri value from firebase(an image download URL from firebase) to download this image in another component, the iteration of forEach freezes. Thank you for your time :)
Warning:[Unhandled promise rejection: TypeError: JSON.stringify cannot serialize cyclic structures.]
observation: When i remove the firebase part imageUri: firebase..., the whole thing works!
the function:
processData = ( data ) => {
console.log('---------data received from loadData(Main.js:70)--------\n', data)
var localProcessedData = [];
Object.entries(data).forEach( ([key, value]) => {
var event = {
id: key,
title: Object.getOwnPropertyDescriptor(value, "eventTitle").value,
imageUri: firebase.storage().ref('events/active/' + key + '/image').getDownloadURL()
}
localProcessedData.push(event);
})
this.setState({
processedData: localProcessedData,
eventsDataIsLoaded: true,
})
}
The type of params the function recieve:
Object {
"-M-I83aV9t1fezOsBn17": Object {
"active": true,
"created": "2020-02-05T02:18:30.772Z",
"description": "Olimpiadas Inter Atletica",
"eventTitle": "oia",
"location": "Uberlandia",
"owner": "p87xn6x8DZTwb6qyTadhkk3UxJV2",
"price": "130",
"startDate": "15",
"time": "14",
"updated": "2020-02-05T02:18:30.772Z",
},
"-M-KlUH-zQhnIhb6wMH8": Object {
"active": true,
"created": "2020-02-05T14:34:20.399Z",
"description": "Cia 2020",
"eventTitle": "Cia",
"location": "Uberlandia",
"owner": "p87xn6x8DZTwb6qyTadhkk3UxJV2",
"price": "130340",
"startDate": "15",
"time": "14",
"updated": "2020-02-05T14:34:20.399Z",
}
}
Expected:
My goal is to transform that whole data in an array like this:
Array [
Object {
"id": "-M-I83aV9t1fezOsBn17",
"title": "oia",
"imageUri": "image url from firebase"
},
Object {
"id": "-M-KlUH-zQhnIhb6wMH8",
"title": "Cia",
"imageUri": "image url from firebase"
}
]
Based on firebase documentation. FIrebase Storage getDownloadUrl is a promise
https://firebase.google.com/docs/reference/js/firebase.storage.Reference.html#get-downloadurl
solution is to implement an async/await
async processData = ( data ) => {
console.log('---------data received from loadData(Main.js:70)--------\n', data)
var localProcessedData = [];
Object.entries(data).forEach( async([key, value]) => {
var event = {
id: key,
title: Object.getOwnPropertyDescriptor(value, "eventTitle").value,
imageUri: await firebase.storage().ref('events/active/' + key + '/image').getDownloadURL()
}
localProcessedData.push(event);
})
this.setState({
processedData: localProcessedData,
eventsDataIsLoaded: true,
})
}
this code is not yet tested.

sort the Json data According to timestamp in Vuejs

I am rending a Json using api
new window.Vue({
el: '#containerwrapper',
data() {
return {
bannerData:""
}
},
created() {
axios.get('http://localhost:8080/pi.json')
.then(response => {
this.bannerData = response.data;
});
},
})
This gives me the Json data as follows
[
{
"id": 118,
"title": "Feuerwerk",
"location": "MUC",
"pressInformation": [
{
"id": 215,
"tstamp": "1577110478",
"created": "2019-09-10T12:13:53+02:00",
"title": "Chemi215",
"teaser": "",
"subline": "Ursachenforschung dauert"
}
]
},
{
"id": 144,
"title": "Testing Stage",
"location": "BER",
"pressInformation": [
{
"id": 254,
"tstamp": "1576838212",
"created": "2019-11-27T13:47:31+01:00",
"title": "Chemi254",
"teaser": "",
"subline": ""
},
{
"id": 250,
"tstamp": "1576838221",
"created": "2019-12-09T12:36:36+01:00",
"title": "Chemi250",
"teaser": "",
"subline": ""
}
]
}
]
I render the data in my template as follows
<div v-for="(eventTitle, i) in bannerData">
<div v-for="(title,index) in eventTitle.pressInformation" :key="title.id">
<div id="pressTimeStamp">{{title.created}} Uhr</div>
<div id="pressTitleTitle">{{title.title}}</div>
<div id="pressTitle">
<h2>{{eventTitle.title}}</h2>
<div id="pressSubline">{{title.subline}}</div>
</div>
</div>
And the output is coming as i expected. Can someone suggest me, how to write a method so my output would be sorted out depends on the 'created' timestamp
new window.Vue({
el: '#containerwrapper',
data() {
return {
bannerData:""
}
},
created() {
axios.get('http://localhost:8080/pi.json')
.then(response => {
response.data.pressInformation.sort(function(a, b){return b['tstamp']-a['tstamp']}));
this.bannerData = response.data;
});
},
})
You can use the sort method with a callback function.
From your data it seems that you already have the timestamp in seconds. It is easy so sort using that.
For example you can write something like this:
arr.sort(function(a, b) {
return +a.pressInformation.tstamp - +b.pressInformation.tstamp;
});
If you are writing a-b denotes ascending order, while b-a is descending order.
The extra + signs are used here to convert from string to int.
Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

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)

cannot update an array of elements via a 2d iteration

I have two arrays of object, the first array (printerChart, around 80 elements) is made of the following type of objects:
[{
printerBrand: 'Mutoh',
printerModel: 'VJ 1204G',
headsBrand: 'Epson',
headType: '',
compatibilty: [
'EDX',
'DT8',
'DT8-Pro',
'ECH',
],
},
....
]
The second array (items, around 500 elements) is made of the following type of objects:
[
{
"customData": {
"brand": {
"value": {
"type": "string",
"content": "hp"
},
"key": "brand"
},
"printer": {
"value": {
"type": "string",
"content": "c4280"
},
"key": "printer"
}
},
"name": "DT8 XLXL",
"image": {
"id": "zLaDHrgbarhFSnXAK",
"url": "https://xxxxxxx.net/images/xxxxxx.jpg"
},
"brandId": "xxxxx",
"companyId": "xxxx",
"createdAt": "2018-03-26T14:39:47.326Z",
"updatedAt": "2018-04-09T14:31:38.169Z",
"points": 60,
"id": "dq2Zezwm4nHr8FhEN"
},
...
]
What I want to do is to iterate via the second array and, if the part of the name of an item (i.e. DT8) is included in an element of the array 'compatibility' of the first array, I would like to include a new properties to it from the element of the first array: printerBrand. I have tried but somehow the iteration doesn't take place correctly. This is what I tried:
items.forEach((item) => {
printerChart.forEach((printer) => {
if (printer.compatibilty.some(compatibleElem => (
item.name.includes(compatibleElem)))) {
item.printerBrand = printer.printerBrand;
} else {
item.printerBrand = '';
}
});
});
What am I doing wrong?
You do
items.items.forEach(...)
Shouldn't you be doing
items.forEach(...)
?
I suggest to initialize item.printerBrand with an empty string and use a nested approach of some for getting a brand and to exit the loops, if found.
This prevents to get an empty string even if there is a brand to assign.
items.forEach((item) => {
item.printerBrand = '';
printerChart.some(printer => {
if (printer.compatibilty.some(compatibleElem => item.name.includes(compatibleElem))) {
item.printerBrand = printer.printerBrand;
return true;
}
});
});

Read API response in Angular2 & ionic

I have successfully get it work to request data from API with http.get in Angular2. This is my http.get
this.http.get('http://localhost:8001/v1/recent', {
headers: headers
})
.map(res => res.text())
.subscribe(
data => console.log(data.total),
() => console.log('API request complete')
);
The API is based on Laravel, it will return data as follows
{
"total": 8,
"per_page": 50,
"current_page": 1,
"last_page": 1,
"next_page_url": null,
"prev_page_url": null,
"from": 1,
"to": 8,
"data": [
{
"id": 1,
"name": "John Doe",
"author": {
"isBlocked": "0",
}
},
{
"id": 1,
"name": "John Doe",
"author": {
"isBlocked": "0",
}
}
]
}
How can I retrieve the JSON object above in Angular2? and all of it's nested array?
console.log(data.total) above is return undefined
The json in your question is not properly formatted, you have an extra comma after "isBlocked":"0" (in line 15 and in line 22)
"author": {
"isBlocked": "0",
}
which will make it a invalid JSON. Preventing Angular from parsing it correctly.
The other issue, you are calling .map(res => res.text()) which will convert your response body to a string not an object. If you want it as a javascript object do .map(res => res.json()) instead.
Here is a working plunker

Categories

Resources