gpt4 book ai didi

javascript - JS 如何在 forEach 循环中从数组中删除一个对象?

转载 作者:行者123 更新时间:2023-11-30 07:49:57 37 4
gpt4 key购买 nike

我有一个包含以下内容的 data 对象:

{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}

我想通过遍历 blocks 来删除具有键 yellowblock,其余数据应按原样保留。所以预期的最终结果是

{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}

数据是动态的,所以我不知道会返回什么,它可能与我的条件匹配,也可能不匹配。

我尝试了很多方法,但到目前为止似乎没有任何效果。如果更容易的话,我也可以使用 lodash。这些似乎都不起作用。感谢任何帮助/指导

1. Using **delete**

const deleteUnwantedBlock = contentObj => {
const updatedData = contentObj;
const blocks = _.get(updatedData, 'blocks', []);

blocks.forEach(block => {
if (block.key.includes('yellow')) {
delete updatedData.block;
}
});
return updatedData;
};

console.log(deleteUnwantedBlock(data.content));```



2. Using rest operator:

const deleteUnwantedBlock = contentObj => {
const blocks = _.get(contentObj, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
let { block, ...restOfTheData } = updatedData;
}
return { ...updatedEntry };
});
};

console.log(deleteUnwantedBlock(data.content));


最佳答案

你只需要过滤:

const obj = {
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
};
obj.content.blocks = obj.content.blocks.filter(({ key }) => key !== 'yellow');
console.log(obj);

关于javascript - JS 如何在 forEach 循环中从数组中删除一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54779690/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com