[英]Sort Ids that are only numbers in an array of objects
我有一個包含用戶內部數據的 JSON 文件
[
{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "mcdonaldholden@xerex.com",
"nameList": [
{
"id": 0,
"name": "Wendi Mooney"
},
{
"id": 2,
"name": "Holloway Whitehead"
}
]
},
{
"_id": "62bd5fbac3e5a4fca5e85e81",
"index": 1,
"nameList": [
{
"id": 0,
"name": "Janine Barrett"
},
{
"id": 1,
"name": "Odonnell Savage"
},
{
"id": 2,
"name": "Patty Owen"
}
]
},
{
"_id": "62bd5fbaf8f417d849c135db",
"index": 2,
"email": "pattyowen@xerex.com",
"nameList": [
{
"id": 0,
"name": "Earline Goff"
},
{
"id": 1,
"name": "Glenna Lawrence"
},
{
"id": 7,
"name": "Bettye Sawyer"
}
]
我必須對每個用戶進行排序:如果用戶有兩個以上的名字,如果用戶 ID 是連續的,如果用戶 ID 是數字
我設法按兩個以上的名字對用戶進行排序,如果 id 是連續的
userData.filter(({nameList}) =>
nameList.length > 2 &&
!nameList.some(({id}, index, array) => index && array[index - 1].id !== id - 1)
);
如果一個對象有一個 id 作為數字,我不應該返回這些對象。 如何在我的代碼中實現它?
輸出應該是滿足過濾器和 some() 標准的所有數組。 也就是說,如果對象的名稱超過 2 個,則其 id 是連續的,並且 id 應該是一個數字。
如果要檢查id
是否為 number類型:
(typeof id == "number")
檢查是否可以轉換為數字
(id == parseInt(id, 10))
然后完整的代碼(你很接近):
var userData = get_data(); userData = userData.filter(function(item) { return item.nameList.length > 2 && item.nameList.every(function(item, index, arr) { return parseInt(item.id) == item.id && (index == 0 || item.id - arr[index - 1].id == 1) }) }) console.log(userData); function get_data() { return [{ "_id": "62bd5fba34a8f1c90303055c", "index": 0, "email": "mcdonaldholden@xerex.com", "nameList": [{ "id": 0, "name": "Wendi Mooney" }, { "id": 2, "name": "Holloway Whitehead" } ] }, { "_id": "62bd5fbac3e5a4fca5e85e81", "index": 1, "nameList": [{ "id": 0, "name": "Janine Barrett" }, { "id": 1, "name": "Odonnell Savage" }, { "id": 2, "name": "Patty Owen" } ] }, { "_id": "62bd5fbaf8f417d849c135db", "index": 2, "email": "pattyowen@xerex.com", "nameList": [{ "id": 0, "name": "Earline Goff" }, { "id": 1, "name": "Glenna Lawrence" }, { "id": 7, "name": "Bettye Sawyer" } ] } ]; }
.as-console-wrapper { max-height: 100% !important }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.