【问题标题】:How to convert 2 object into single one如何将 2 个对象转换为单个对象
【发布时间】:2022-01-15 10:23:05
【问题描述】:

我有 2 个对象

const size = shoppingCart.map((el) => ({size: el.size}));

第一个是filteredProducts列表:

    const filteredProducts = [
    {
        description: "Material: 100% cotton\nCare instructions: Do not tumble dry, machine wash at 30 ° C, machine wash on gentle cycle",
        id: "80005397",
        image: {url: 'h,ttps://www.datocms-assets.com/59095/1638273249-spodnie.png'},
        price: 32.8,
        title: " Pier One Cargo"
    }
]

第二个是选定的尺寸:

  const selectedSize = [
    {
        size: 'L'
    }
]

我必须像这样将这两个对象组合成一个对象:

    const filteredProducts = [
    {
        description: "Material: 100% cotton\nCare instructions: Do not tumble dry, machine wash at 30 ° C, machine wash on gentle cycle",
        id: "80005397",
        image: {url: 'h,ttps://www.datocms-assets.com/59095/1638273249-spodnie.png'},
        price: 32.8,
        title: " Pier One Cargo",
        size: 'L'
    }
]

【问题讨论】:

  • filteredProducts.size = selectedSize.size ??
  • 您可能正在寻找Object.assign
  • 两个数组的长度总是相同的?
  • 是的,长度总是一样的
  • 问题不清楚。两个数组的大小总是相同吗?或者这些数组是否只包含一个您想要合并的对象?

标签: javascript reactjs object


【解决方案1】:

您可以使用 map() 函数和spread operator:

const filteredProductsWithSize = filteredProducts.map((product, i) => ({
    ...product,
    ...selectedSize[i]
}));

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多