[英]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.