![](/img/trans.png)
[英]How to loop through array of objects and create a new array of objects with only certain properties using typescript and react?
[英]how to exclude only certain elements in json objects of array using for loop?
我想僅在所有“名稱”,“年齡”,“類別”字段都不為null時才調用函數checkIsObjectEmptyOrNot
。 如果所有這些值(沒有id和book_id)都為null,則該函數應返回false。 id
和book_id
應該從此過濾過程中排除,因為id
和book_id
始終對Laravel后端有價值。
checkIsObjectEmptyOrNot(object){
for (var key in object) {
if (key != 'id' && key != 'book_id' && key != null) {
break;
return true;
}
}
return false;
}
我有一個Json數組,
[
{
"id": 1,
"book_id": 2,
"name": "myname",
"age": 25,
"class":null,
},
{
"id": 2,
"book_id": 2,
"name": "myname2",
"age": 25,
"class": null,
},
{
"id": 3,
"book_id": 2,
"name": "myname3",
"age": 25,
"class": 10,
},
]
您可能不需要為此使用新功能。 Array.filter
可以完成這項工作。 請參見下面的代碼段。 將返回所有有效項。
const arr = [ { "id":1, "book_id":2, "name":"myname", "age":25, "class":null, }, { "id":2, "book_id":2, "name":"myname2", "age":25, "class":null, }, { "id":3, "book_id":2, "name":"myname3", "age":25, "class":10, }, ].filter((item)=>{ return item.name && item.age && item.class }) console.log(arr);
但是,如果您需要一個功能,可以這樣
const arr = [{ "id": 1, "book_id": 2, "name": "myname", "age": 25, "class": null, }, { "id": 2, "book_id": 2, "name": "myname2", "age": 25, "class": null, }, { "id": 3, "book_id": 2, "name": "myname3", "age": 25, "class": 10, }, ] function checkIsObjectEmptyOrNot(object) { for (var key in object) { if (key !== 'id' && key !== 'book_id' && object[key] !== null) return true; } return false; } console.log(checkIsObjectEmptyOrNot(arr[0])); console.log(checkIsObjectEmptyOrNot(arr[1])); console.log(checkIsObjectEmptyOrNot(arr[2]));
如果所有有這將返回真name
, age
和class
不null
或undefined
或false
和true
,否則
希望這可以幫助 :)
您可以嘗試使用forEach
。
var arr = [
{
"id":1,
"book_id":2,
"name":"myname",
"age":25,
"class":null,
},
{
"id":2,
"book_id":2,
"name":"myname2",
"age":25,
"class":null,
},
{
"id":3,
"book_id":2,
"name":"myname3",
"age":25,
"class":10,
},
]
var flag = 0;
arr.forEach(function(singleObject){
for (let [key, value] of Object.entries(singleObject)) {
if(singleObject[key] != _id || singleObject[key] != book_id){
if(singleObject[key] != null){
flag = 1;
}
}
}
});
//if condition satisfies if all the value is null except _id and book_id
if(flag == 0 ){
//call function.
checkIsObjectEmptyOrNot()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.