I can't figure out how to remove and object inside a deep nest array of object pointing it by it's id value.
Here is my code using reduce. I wanted to recreate the array on each itteration by its a big mess (and it's only going through the index 0).
I would like to remove this whole piece by pointing the node id 35993. If the node get a children this would remove the children as well.
const array = [
{
node: {
level: 0,
id: 71,
type: "block",
style: {
backgroundColor: "#548444",
},
},
children: [
{
node: {
id: 85,
type: "block",
style: {
backgroundColor: "#548444",
fontSize: "19px",
},
},
children: [
{
node: {
id: 955,
type: "column",
style: {
backgroundColor: "#eee",
fontSize: "28px",
},
},
children: [
{
node: {
level: 3,
parentId: 71,
id: 732,
type: "text",
data: {
text: "Ceci est un text",
},
style: {
color: "blue",
fontSize: "13px",
},
},
},
{
node: {
id: 353,
parentId: 71,
type: "text",
data: {
text: "Ceci est un text",
},
style: {
color: "blue",
fontSize: "13px",
},
},
},
],
},
],
},
],
},
{
node: {
level: 0,
id: 7991,
type: "block",
style: {
backgroundColor: "#548444",
},
},
children: [
{
node: {
id: 8995,
type: "block",
style: {
backgroundColor: "#548444",
fontSize: "19px",
},
},
children: [
{
node: {
id: 95995,
type: "column",
style: {
backgroundColor: "#eee",
fontSize: "28px",
},
},
children: [
{
node: {
level: 3,
parentId: 71,
id: 73992,
type: "text",
data: {
text: "Ceci est un text",
},
style: {
color: "blue",
fontSize: "13px",
},
},
},
{
node: {
id: 35993,
parentId: 71,
type: "text",
data: {
text: "Ceci est un text",
},
style: {
color: "blue",
fontSize: "13px",
},
},
},
],
},
],
},
],
},
];
const search1 = (arr, itemId, nestingKey) =>
arr.reduce((a, item) => {
if (a) return a;
if (item.node.id === itemId) return item;
if (item[nestingKey]) return search(item[nestingKey], itemId, nestingKey);
}, null);
const remove = function (arr, itemId, nestingKey) {
let newArr = [];
arr.reduce((a, item) => {
if (item.node.id !== itemId) {
const tempItem = {
...item,
};
newArr.push(tempItem);
}
if (item.node.id === itemId) {
delete item.node;
return item;
}
if (item[nestingKey]) return remove(item[nestingKey], itemId, nestingKey);
}, null);
return newArr;
};
const res = remove(array, 35993, "children");
console.log(JSON.stringify(res));
Comments
Post a Comment