javascript - 根据条件在嵌套的 JS 数组中插入新的 JSON 对象

对于我的电子商务应用程序要求之一,我有一个嵌套数组(示例):

const data = [
    {
        "id": 1,
        "group": "upper-wear",
        "labels": [
            {
                "type": "shirts",
                "quantity": "20",
            },
        ],
        popular: true
    },
    {
        "id": 2,
        "group": "bottom-wear",
        "lables": [
            {
                "type": "trousers",
                "quantity": "31",
            },
        ],
        popular: true
    },
]

对于这个数组,如果组值等于“upper-wear”,我需要将新对象插入到数组“labels”中。

const newDataToInsert = [
    {
      "type": 'blazers',
      "quantity": 19
    },
  ]

这是我到目前为止尝试过的,考虑到现在我只需要插入单个标签(即'upper-wear')(将来,可以有多个标签类别'upper-wear','bottom- wear', 被插入):

const updatedArray = data.map((datum) => {
    if (datum.group === 'upper-wear') {
      return {
        ...datum,
        labels: [...datum.labels, ...newDataToInsert]
      };
    }
  });
  
  console.log(updatedArray);

但似乎有一个愚蠢的问题我遗漏了,因为结果返回如下:

[
  {
    id: 1,
    group: 'upper-wear',
    labels: [ [Object], [Object] ],
    popular: true
  },
  undefined
]

我知道可能有更好的方法可用,但这是我目前认为的最低解决方案。

任何解决当前或任何更好解决方案的帮助将不胜感激。

最佳答案

试试这个

updatedArray = data.map((d) => {
    if (d.group && d.group === 'upper-wear') {
        return { ...d, labels: d.labels.concat(newDataToInsert) }
    } else {
        return d;
    }
})

const data = [
{
    "id": 1,
    "group": "upper-wear",
    "labels": [
        {
            "type": "shirts",
            "quantity": "20",
        },
    ],
    popular: true
},
{
    "id": 2,
    "group": "bottom-wear",
    "lables": [
        {
            "type": "trousers",
            "quantity": "31",
        },
    ],
    popular: true
},
];

const newDataToInsert = [
{
  "type": 'blazers',
  "quantity": 19
},
  ];

const updatedArray = data.map((d) => {
if (d.group && d.group === 'upper-wear') {
    return { ...d, labels: d.labels.concat(newDataToInsert) }
} else {
    return d;
}
});
  console.log(updatedArray)

解释

这里在映射数据时,我们检查条件

如果

  • 如果匹配,我们将首先从变量 b 复制整个对象 return { ...b }
  • 之后我们取另一个同名变量 lables return { ...d, labels: d.labels.concat(newDataToInsert) },根据JSON 默认性质,同名的新变量将保存最新值
  • 这里在labels中,我们首先获取旧数据的副本,然后将其与newDataToInsert数组labels: d.labels.concat(newDataToInsert)合并,它将合并2数组并将它们存储在 JSON 中,名称为 labels

否则

  • 否则我们只返回当前值 else { return d; }

https://stackoverflow.com/questions/71751692/

相关文章:

c - 为什么静态链接的 "hello world"程序这么大(超过 650 KB)?

linux - bash 将奇数日期格式转换为 linux 日期识别的更有效方法

c# - C# 中的 StringBuilder 与 Span

go - 函数参数的求值顺序是什么?

python - `__ge__` 在 dict.values() 上使用时失败

c# - System.IO.Directory.Exists 在 LINQ 语句中失败,但在 fo

sql - 如何使用 group by 检索不同的数据

haskell - 在 Haskell 中日志记录功能的不同实现之间切换的有效方法?

java - 如何在 Java 中创建包含运算符的变量?

ios - 在 SwiftUI 中声明 Binding 属性有什么区别?