0

I'm trying to filter out unwanted objects from a parent object
But I'm being thrown an error of TypeError: Cannot delete property 'children' of #<Object>


Props passed like this:

<Column df={["between", "mt-0", "around"]} xl={["center"]}>...</Column>

Given to a utility function like this:

const Column = props => {
  const x = filterComponentProps(props)
  return stuff
}

The inside the utility function anything within the object not matched within const condition = ["df", "xl"] is to be removed.

export const filterComponentProps = props => {
  let data = props
  console.log(data) 
  // {df: Array(3), xl: Array(1), children: Array(6)}
  // children: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
  // df: (3) ["between", "mt-0", "around"]
  // xl: ["center"]

  const condition = ["df", "xl"]
  Object.keys(data).forEach(key =>
    !condition.includes(key) ? delete data[key] : key
  ) //ERROR 
  return data
}

I set up a test to see if its a problem with the function but it works as expected:

const data = {
  df: { name: "Part 1", size: "20", qty: "50" },
  xl: { name: "Part 2", size: "15", qty: "60" },
  children: { name: "Part 2", size: "15", qty: "120" },
}

const condition = ["df", "xl"]

Object.keys(data).forEach(key =>
  !condition.includes(key) ? delete data[key] : key
)

console.log(data)
//{df: {…}, xl: {…}}
//df: {name: "Part 1", size: "20", qty: "50"}
//xl: {name: "Part 2", size: "15", qty: "60"}

2 Answers 2

1

you get this error because you try to modify the object which is freezed. If you try the following

const data = Object.freeze({
  df: { name: "Part 1", size: "20", qty: "50" },
  xl: { name: "Part 2", size: "15", qty: "60" },
  children: { name: "Part 2", size: "15", qty: "120" },
})

you get the same error. Let me know if it's clear.

Sign up to request clarification or add additional context in comments.

Comments

0

Destructure the props like this,

let data = {...props};

create a shallow copy of props, now loop over data and delete the property you want,

export const filterComponentProps = props => {
  let data = {...props};     // shallow copy
  const condition = ["df", "xl"]
  Object.keys(data).forEach(key =>
    !condition.includes(key) ? delete data[key] : key
  )
  return data;
}

try this, it will work.

1 Comment

Nail on the head. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.