Javascript ES6 将对象数组拆分为两个不同的对象子数组

如何解决Javascript ES6 将对象数组拆分为两个不同的对象子数组

我有一个名为 obj.credits: [] 的对象或 json 数组,其中包含大约 50 个信用对象。每个信用对象都有一个 cast_id 字段,该字段为 null 或非 null

我想将所有具有 null cast_id 的对象完全过滤到一个子数组 obj.credits.crew: [] 中,并将所有不为 null cast_id 的对象过滤到另一个子数组 obj.credits.cast: [] 中。

之后 obj.credits 应该只包含键 castcrew

以下不起作用。它创建子数组但不删除原始数组对象

 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 是一个数组。您不能在其中添加 castcrew 属性。 所以你可以创建 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?