I have a json file and I'm trying to remove an element with below code .
exports.delete = function(req, res) {
var deletearticle = articles[req.params.id];
delete articles[req.params.id];
fs.writeFile('server/articles.json',JSON.stringify(articles, null, 4),finished);
function finished(err){
console.log("--->After deletion, article list:\n" + JSON.stringify(articles, null, 4) );
}
res.end(JSON.stringify(deletearticle, null, 4));
};
after removing the element my json file will be like :
[
{
"header": "Jack",
"body": "Davis",
"date": "",
"id": 0
},
null,
{
"header": "dfd",
"body": "dgfgfgfgfdgfg",
"date": "2018-11-24T16:33:48.842Z",
"id": 2
}]
and I get error on client side :
{articles ? articles.map(({ id, header ,body}) => (
<div key={id} timeout={500} className="fade">
<div className="article">
<h2 className="article_title">{header}</h2>
Because one of my JSON's element is null it says that can't read id from null.Is There any better way to remove this element from my json file ? or i can check if srticle is not null in client side.
Just filter your object, Assume here a is your JSON array and you have to filter all object which does not have null
a = a.filter(function(obj){ if(obj != null) return obj })
Now print a, It will filter out all object except null objects
You can use array.splice to remove object from an array, as you have id of an object, you first need to find the index of an object to be removed and then you can remove it easily using splice.
For your reference avoid using delete
var sampleArray= [{
"header": "Jack",
"body": "Davis",
"date": "",
"id": 5
},
{
"header": "Jack",
"body": "Davis",
"date": "",
"id": 6
},
{
"header": "dfd",
"body": "dgfgfgfgfdgfg",
"date": "2018-11-24T16:33:48.842Z",
"id": 7
}
];
var id = 5;
var index = sampleArray.findIndex(a=> a.id === id);
if (index > -1) {
sampleArray.splice(index, 1);
}
console.log(sampleArray);
You can delete element without keeping null like this...
array.splice(index, 1);
Or,You can remove null elements by doing like this...
var array = [
{
"header": "Jack",
"body": "Davis",
"date": "",
"id": 0
},
null,
{
"header": "dfd",
"body": "dgfgfgfgfdgfg",
"date": "2018-11-24T16:33:48.842Z",
"id": 2
}];
// filter array
var filtered = array.filter(function (el) {
return el != null;
});
var a = [
{
"header": "Jack",
"body": "Davis",
"date": "",
"id": 0
},
null,
{
"header": "dfd",
"body": "dgfgfgfgfdgfg",
"date": "2018-11-24T16:33:48.842Z",
"id": 2
}];
//using es6 array.filter to filter null or undefined or empty object
var filtered = array.filter((x)=>{
for (var key in filter) {
if (x[key] === undefined || x[key] !== null || x[key]!=='')
return false;
}
return true;
});
Related
I have this json :
{
"meta": {
"status": 200,
"pagination": {
"page": 1,
"perPage": 15,
"hasNext": true
}
},
"data": [
{
"id": "1",
"title": "Movie title1"
"rating": null,
"playProviders": [
]
},
{
"id": "2",
"title": "Movie title2"
"rating": {
"ratingAssessment": "7.1"
},
"playProviders": [
"HBO", "Netflix"
]
},
....
}
I want to create a page with a list of movies, I need to fetch movies but only those which have a rating and playProviders, what parameters should I use in this request?
https://api.com/movies?orderBy=views
When I filters in the code:
programs.filter((program) => program.rating !== null);
it only gets a few films per page, those that don't have null. For example, 15 are per page and I get 2. How do I filter this? (I am using react typescript)
I don't have access to the API code. I need to filter what is returned by the API or write a query so that you get already filtered data from the API.
programs = [
{rating: 1,
playProviders: ["sf"]
},
{
rating: 4,
playProviders: []
}
]
programs.filter(function(program) {
if (program.rating !== null && program.playProviders.length !== 0) {
return program;
}
})
I need your opinion in this situation:
I get from API with this function:
getRS(
idProject: string
): Observable<ResponseModel<RSModel>> {
return this.http.get<ResponseModel<RSModel>>(
ApiUrlsConfig.getRS(
idProject
)
);
}
this response:
{
"data": [
{
"id": "id1",
"state": 1,
"note": null
},
{
"id": "id1",
"state": 2,
"note": "Reason 1"
},
{
"id": "id2",
"state": 2,
"note": "Reason updated3",
}
],
"result": null
}
I need to use filter in this response because I should be get the last state for each id. For example, I want to display state 2 in item with id: id1. For this I want to use filter. The problem is because I can't use filter on it, I don't understand why.
I tried to write this code:
#Input() set jobId(jobId: string) {
this.optionsService
.getRS(
this.idProject
)
.pipe()
.subscribe((res) => {
let resId = res.filter((aaa)=>{
if(aaa.id === jobId){
res.slice(-1)[0].id
}
}
)
});
}
Not function.
Please can you share with me any idea?
Thank you
Try this logic:
Loop backwards throw it.
Loop backwards over index to the start.
Splice duplicates.
let response = {
"data": [
{
"id": "id1",
"state": 1,
"note": null
},
{
"id": "id1",
"state": 2,
"note": "Reason 1"
},
{
"id": "id2",
"state": 2,
"note": "Reason updated3"
}
],
"result": null
}
let data = response.data;
for (let i = data.length - 1; i >= 0; i--) {
for (let j = i - 1; j >= 0; j--) {
if (data[i].id === data[j].id) {
data.splice(j, 1);
j++;
}
}
};
console.log(data);
try this:
if(aaa.id == jobId){
return res.slice(-1)[0].id
}
I have a two array response and I would like to compare the two responses and have to filter the unmatched array elements into a new array object.
Condition to compare the two response and filter is: we have to filter when code and number are not matched exactly with the response two then we have to filter such an array element into a new array object which I need as an output.
The Array element present in the Response two example is also present in the Response of Array One example which I don't want and I need to filter the array elements which is not matched with the Response of Array One.
Final Output which we filtered from the response two array will be like below which is unmatched with the response 1 array object:
{
"unmatchedArrayRes": [
{
"code": "08",
"number": "2323232323",
"id": "432",
"value": "value432"
}
]
}
Response of Array One
{
"MainData": [
{
"DataResponseOne": [
{
"viewData": {
"number": "11111111111111",
"code": "01"
},
"name": "viewDataOne"
},
{
"viewData": {
"number": "22222222222222",
"code": "01"
},
"name": "viewDataTwo"
},
{
"viewData": {
"number": "3333333333333",
"code": "02"
},
"name": "viewDataThree"
}
]
},
{
"DataResponseTwo": [
{
"viewData": {
"number": "5555555555555",
"code": "9090"
},
"name": "viewDataFour"
},
{
"viewData": {
"number": "6666666666666",
"code": "01"
},
"name": "viewDataFive"
},
{
"viewData": {
"number": "8888888888888",
"code": "01"
},
"name": "viewDataSix"
}
]
}
]
}
Response Two Example :
{
"compareRes": [
{
"code": "01",
"number": "11111111111111",
"id": "123",
"value": "value123"
},
{
"code": "9090",
"number": "5555555555555",
"id": "345",
"value": "value567"
},
{
"code": "08",
"number": "2323232323",
"id": "432",
"value": "value432"
}
],
"metaData": "343434343434"
}
First, create a combined list of all the view items from response one.
const combinedList = [];
res1["MainData"].forEach(data => {
// console.log(data);
for( let key in data) {
// console.log(key);
data[key].forEach(innerData => {
console.log(innerData)
combinedList.push(innerData["viewData"]);
})
}
});
In the above method, It is done in such a way that it can handle multiple viewData responses like DataResponseOne, DataResponseTwo, and so on.
And then filter second response Items like this:
const unfilteredListItems = res2["compareRes"].filter(data => {
return !combinedList.some(listItem => {
return listItem.code === data.code && listItem.number === data.number;
});
});
console.log(unfilteredListItems);
Working Stackblitz link: https://stackblitz.com/edit/ngx-translate-example-aq1eik?file=src%2Fapp%2Fapp.component.html
Please see the link
http://plnkr.co/edit/Cn0sNDGEkPOzV19ye8NW?p=preview
I have changed my JSON, then I can't able to filter the data.
var result = $filter('filter')(foo.results, {id:2426})[0];
if you limit on your JSON data
and you can make sure the data property value is num
maybe you can try this ...
var foo = {
"count": 70,
"language": "en",
"0": {
"id": "2420",
"name": "Medical Center"
},
"1": {
"id": "7840",
"name": "Conference Room"
},
"2": {
"id": "2426",
"name": "Deck 5 Starboard"
}
};
foo.results = [];
for(var property in foo){
if(property == parseInt(property, 10).toString()){
foo.results.push(foo[property]);
}
}
var result = $filter('filter')(foo.results, {id:2426})[0];
$scope.name = result.name;
wish help !!
I want to create a treeview array for use in Angular UI Tree. I want to create the structure from a array of object like this:
0: Object
body: null
categoryDescription: null
categoryTopic: null
description: null
faqBodyId: 0
faqCategoryId: 0
faqGroupId: 1
groupDescription: null
groupName: "Generelt"
groupTopic: "Generelt"
themeCode: "GEN"
topic: null
1: Object body: null categoryDescription: "Test af kategori" categoryTopic: "Mail" description: null faqBodyId: 0 faqCategoryId: 2 faqGroupId: 1 groupDescription: null groupName: null groupTopic: null themeCode: null topic: null
2: Object body: "This is a test" categoryDescription: null categoryTopic: null description: "Testing" faqBodyId: 3 faqCategoryId: 2 faqGroupId: 0 groupDescription: null groupName: null groupTopic: null themeCode: null topic: "Test123"
etc...
It is in three levels. Group, Category and Body
A node does not allways have a child!
I want It in this structure and three levels:
[
{
"id": 1,
"title": "1. dragon-breath",
"items": []
},
{
"id": 2,
"title": "2. moiré-vision",
"items": [
{
"id": 21,
"title": "2.1. tofu-animation",
"items": [
{
"id": 211,
"title": "2.1.1. spooky-giraffe",
"items": []
},
{
"id": 212,
"title": "2.1.2. bubble-burst",
"items": []
}
]
},
{
"id": 22,
"title": "2.2. barehand-atomsplitting",
"items": []
}
]
},
{
"id": 3,
"title": "3. unicorn-zapper",
"items": []
},
{
"id": 4,
"title": "4. romantic-transclusion",
"items": []
}
]
Structure
How is that done with Angular code?
I solved the problem like this.
The input array is sorted:
function buildtree(arr) {
var group = [];
angular.forEach(arr, function (value, index) {
if (value.faqGroupId > 0 && value.faqCategoryId == 0 && value.faqBodyId == 0) {
var category = [];
var faqgroup = {
"id": value.faqGroupId,
"title": value.groupTopic,
"description": value.groupDescription,
"name": value.groupName,
"items": category
}
angular.forEach(arr, function (valuecat, index) {
if (value.faqGroupId == valuecat.faqGroupId && valuecat.faqCategoryId > 0 && valuecat.faqBodyId == 0) {
var body = [];
var faqcat = {
"id": valuecat.faqCategoryId,
"title": valuecat.categoryTopic,
"description": valuecat.categoryDescription,
"items": body
}
angular.forEach(arr, function (valuebod, index) {
if (valuecat.faqGroupId == valuebod.faqGroupId && valuecat.faqCategoryId == valuebod.faqCategoryId && valuebod.faqBodyId > 0) {
var faqbody = {
"id": valuebod.faqBodyId,
"title": valuebod.topic,
"description": valuebod.description,
"body": valuebod.body,
}
body.push(faqbody);
}
})
category.push(faqcat);
}
})
group.push(faqgroup);
}
});
return group;
}
Array list :
Flat object array list
var dataList= [
{'id':1 ,'parentid' : 0, 'label'="label 1"},
{'id':4 ,'parentid' : 2 ,'label'="label 2"},
{'id':3 ,'parentid' : 1, 'label'="label 3"},
{'id':5 ,'parentid' : 0, 'label'="label 4"},
{'id':6 ,'parentid' : 0, 'label'="label 5"},
{'id':2 ,'parentid' : 1, 'label'="label 6"},
{'id':7 ,'parentid' : 4, 'label'="label 7"},
{'id':8 ,'parentid' : 1, 'label'="label 8"}
];
covert flat object array list to treeview list
function flatListToTreeViewData(dataList) {
var tree = [],
mappedArr = {},
arrElem,
mappedElem;
for (var i = 0, len = dataList.length; i < len; i++) {
arrElem = dataList[i];
mappedArr[arrElem.id] = arrElem;
mappedArr[arrElem.id]['children'] = [];
}
for (var id in mappedArr) {
if (mappedArr.hasOwnProperty(id)) {
mappedElem = mappedArr[id];
array of children.
if (mappedElem.parentID) {
mappedArr[mappedElem['parentID']]['children'].push(mappedElem);
}else {
tree.push(mappedElem);
}
}
}
return tree;
}