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

发布于 2025-01-19 11:28:20 字数 1237 浏览 2 评论 0原文

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

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((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
]

我知道可能有更好的方法,但这是我现在可以认为的最低解决方案。

任何帮助解决当前或任何更好解决方案的帮助都将受到高度赞赏。

For one of my e-commerce application requirement, I have a nested array of the form (Sample):

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
    },
]

To this array, I need to insert new objects to the array 'labels' if the group value equals 'upper-wear'.

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

This is what I tried so far, considering that for now I only need to insert to single label (i.e. 'upper-wear') (in future, there can be multiple labels category 'upper-wear', 'bottom-wear', to be inserted into):

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

But there seems to be a silly issue that I am missing as the result returns like this:

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

I know there may be better approaches available, but this is what I can think of as the minimum solution for now.

any help to resolve the current or any better solution will be highly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

帅冕 2025-01-26 11:28:20

尝试用这个

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)

解释

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

IF

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

Else

  • 在 else 中我们只是返回当前值<代码> else { 返回 d; }

Try with this

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)

Explaination

Here while mapping the data, we check for the condition

IF

  • If it matches then we will first copy the whole object from the variable b return { ...b }
  • after that we take another variable with the same name lables return { ...d, labels: d.labels.concat(newDataToInsert) },As per the JSON default nature the new variable with the same name will hold the latest value
  • Here in labels we first take a copy of old data and then merge it with newDataToInsert array labels: d.labels.concat(newDataToInsert), It will merge 2 arrays and store them in JSON with the name labels

Else

  • In else we just return the current values else { return d; }
撞了怀 2025-01-26 11:28:20

您实际上不需要使用 map 遍历数组。只需在数组中找到一个对象并更改您想要的内容即可。

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

data.find(({ group }) => group === 'upper-wear')?.labels.push(...newDataToInsert);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You don't actually need to iterate with map over the array. Just find an object in the array and change what you want.

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

data.find(({ group }) => group === 'upper-wear')?.labels.push(...newDataToInsert);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

遥远的绿洲 2025-01-26 11:28:20

您不会返回地图中的所有对象。仅当满足您的条件时您才会返回结果。这会导致您未定义的对象......

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(datum => { 
    if (datum.group === 'upper-wear') datum.labels = [...datum.labels,  ...newDataToInsert]
    return datum     
});
  
console.log(updatedArray);

You're not returning all objects from your map. you're only returning a result when your criteria is met. This is resulting in your undefined objects...

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(datum => { 
    if (datum.group === 'upper-wear') datum.labels = [...datum.labels,  ...newDataToInsert]
    return datum     
});
  
console.log(updatedArray);

°如果伤别离去 2025-01-26 11:28:20

您可以使用 Array#find 来定位所需的组,然后更改找到的组的标签。有两个选项,具体取决于您要插入的项目数量。使用Array#push添加想要的项目;对多个项目使用 forEach

const searchgroup = "upper-wear";
const target = data.find(({group}) => group === searchgroup);
target.labels.push(...newDataToInsert); //For one item to insert
//newDataToInsert.forEach(label => target.labels.push( label )); //For more than one item

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

//group to find
const searchgroup = "upper-wear";
//target element in data
const target = data.find(({group}) => group === searchgroup);
//check if group was found
if( target ) {
    //if there's only one product in newDataToInsert us this:
    //target.labels.push(...newDataToInsert);

    //if you have more than one product to be inserted use this; also works for one
    newDataToInsert.forEach(label => target.labels.push( label ));
} else {
    console.log( `No such group found: ${searchgroup}!` );
}

console.log( data );

You can use Array#find to locate the desired group and then change labels for the group found. There are two options depending on how many items you would like to insert. Use Array#push to add the desired item; use forEach for more than one item:

const searchgroup = "upper-wear";
const target = data.find(({group}) => group === searchgroup);
target.labels.push(...newDataToInsert); //For one item to insert
//newDataToInsert.forEach(label => target.labels.push( label )); //For more than one item

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

//group to find
const searchgroup = "upper-wear";
//target element in data
const target = data.find(({group}) => group === searchgroup);
//check if group was found
if( target ) {
    //if there's only one product in newDataToInsert us this:
    //target.labels.push(...newDataToInsert);

    //if you have more than one product to be inserted use this; also works for one
    newDataToInsert.forEach(label => target.labels.push( label ));
} else {
    console.log( `No such group found: ${searchgroup}!` );
}

console.log( data );

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文