【问题标题】:Javascript ES6 split object array into two different object subarraysJavascript ES6 将对象数组拆分为两个不同的对象子数组
【发布时间】:2021-09-14 15:58:18
【问题描述】:

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

我想将所有具有 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)

【问题讨论】:

  • 请提供minimal reproducible example。 “不工作”是什么意思?
  • 我不确定数组如何添加两个属性。好像有点奇怪,为什么不新建一个对象呢?
  • “不工作”我的意思是它创建了两个子数组,但原始数组项没有被删除。假设总共有 50 个对象,其中 25 个为空 cast_id,其他 25 个不为空 cast_id
  • 因为它是一个数组,而不是一个对象。如果您不想要该数组,请将其替换为对象。
  • 过滤器不会改变原始数组。你也不能做 newArray.x = 123;其中 newArray 是一个数组。

标签: javascript arrays ecmascript-6 filter reduce


【解决方案1】:

要从列表中删除所有可迭代元素,请将其长度设置为零。下面的例子。

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))

【讨论】:

    【解决方案2】:

    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};
    

    【讨论】:

      【解决方案3】:

      你遇到的问题是你的行为就像一个数组是一个对象。您只是将属性添加到数组中。如果你想让它成为一个对象,你需要重新考虑你是如何做到这一点的。

      因此,您想要一个具有两个包含数组的属性的对象的最终输出,因此将 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: [] });
      

      【讨论】:

        【解决方案4】:

        这不是一个很容易理解的问题。 解决这个问题(这将起作用)的漫长方法是初始化两个新数组(credits.crew 和 credits.cast),循环遍历主数组,检查键是否为空,然后将该记录添加到新数组之一数组。 这假设您有对象的 write 方法来获取它的值。

        【讨论】:

          【解决方案5】:

          这样,您不必为了将演员与工作人员分开而遍历数组两次。

          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;
          

          【讨论】:

            猜你喜欢
            • 2015-10-16
            • 2021-12-13
            • 1970-01-01
            • 1970-01-01
            • 2022-08-18
            • 2016-02-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多