[英]Javascript ES6 split object array into two different object subarrays
我有一個名為obj.credits: []
的對象或 json 數組,其中包含大約 50 個 credit 對象。 每個信用對象都有一個為空或不為空的cast_id
字段
我想將所有具有 null cast_id
對象完全過濾到一個子obj.credits.crew: []
並將所有不具有 null cast_id
對象cast_id
到另一個子obj.credits.cast: []
。
之后obj.credits
應該只包含鍵cast
和crew
。
以下不起作用。 它創建子數組但不刪除原始數組對象
obj.credits.cast = obj.credits.filter(credit => credit.cast_id != null)
obj.credits.crew = obj.credits.filter(credit => credit.cast_id == null)
你遇到的問題是你的行為就像一個數組是一個對象。 您只是向數組添加屬性。 如果你想讓它成為一個對象,你需要重新思考你是如何做到這一點的。
因此,您需要一個具有兩個包含數組的屬性的對象的最終輸出,因此將 obj.credits 替換為一個對象。
obj.credits = obj.credits.reduce((acc, credit) => {
if (credit.cast_id != null) acc.cast.push(credit);
else acc.crew.push(credit);
return acc;
}, { cast: [], crew: [] });
obj.credits
是一個數組。 您不能在其中添加演員和工作人員屬性。 所以你可以創建 2 個單獨的子陣列 -
let cast = obj.credits.filter(credit => credit.cast_id != null)
let crew = obj.credits.filter(credit => credit.cast_id == null)
然后清除obj.credits
數組並將其初始化為一個對象。 然后將這些子數組添加為屬性。
obj.credits = {};
obj.credits = {cast, crew};
這樣,您不必為了將演員表與工作人員分開而遍歷數組兩次。
const cast = [];
const crew = [];
for (const item of obj.credits){
if (!item) continue;
if (item.cast_id) cast.push(item);
else crew.push(item);
}
obj.credits.cast = cast;
obj.credits.crew = crew;
不是一個很容易理解的問題。 解決這個問題的很長的路(這會起作用)是初始化兩個新數組(credits.crew 和 credits.cast),循環遍歷主數組檢查鍵是否為空,然后將該記錄添加到新數組之一數組。 這假設您在對象上擁有 write 方法來獲取其值。
要從列表中刪除所有可迭代元素,請將其長度設置為零。 下面舉例。
let obj = {} obj.credits = [ {cast_id: 1}, {cast_id: 2}, {cast_id: null} ] obj.credits.cast = obj.credits.filter(credit => credit.cast_id != null) obj.credits.crew = obj.credits.filter(credit => credit.cast_id == null) // remove all elements from `credits` property of `obj` obj.credits.length = 0 document.write(JSON.stringify(obj), '<br>') document.write(JSON.stringify(obj.credits), '<br>') document.write(JSON.stringify(obj.credits.cast), '<br>') document.write(JSON.stringify(obj.credits.crew))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.