如何解决Javascript ES6 将对象数组拆分为两个不同的对象子数组
我有一个名为 obj.credits: []
的对象或 json 数组,其中包含大约 50 个信用对象。每个信用对象都有一个 cast_id
字段,该字段为 null 或非 null
我想将所有具有 null cast_id
的对象完全过滤到一个子数组 obj.credits.crew: []
中,并将所有不为 null 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。
select 1 where isnumeric('20210702') = 1 and try_cast('20210702' as date) is not null
,
obj.credits
是一个数组。您不能在其中添加 cast 和 crew 属性。
所以你可以创建 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))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。