0

In a ReactJS project I have the following object array:

const arr = [
    {
        key1: 1,
        key2: 'value1'
    },
    {
        key1: 2,
        key2: 'value2'
    },
    {
        key1: 3,
        key2: ''    // empty string, therefore I do not want to pass this object in the array to be passed to the prop
    }
]

And I'm passing the above array to a prop as follows:

<Component
    Array={arr}
/>

Problem

I do not want to pass any object with key 'b' being an empty string (like the second object according to the example).

Is there any way that I can pass the rest of the objects as an array without the object whose key 'b' has an empty string?

2
  • 1
    before you pass it use arr.filter(({key2}) => !!key2) Commented Apr 29, 2022 at 16:46
  • Thank you so much. but I do not get why there are two ! operators? Could you please explain a little bit? Commented Apr 29, 2022 at 16:49

1 Answer 1

1

You can pass a filtered array to the component that doesn't contain objects where key2 is an empty string:

<Component
    Array={arr.filter(({key2}) => key2 !== "")}
/>

React example below:

function App() {
  const items = [
    { key1: 1, key2: "value1" },
    { key1: 2, key2: "value2" },
    { key1: 3, key2: "" },
  ];
  return <List items={items.filter(({ key2 }) => key2 !== "")} />;
}

function List({ items }) {
  return (
    <ul>
      {items.map((item) => (
        <li>{JSON.stringify(item, null, 2)}</li>
      ))}
    </ul>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>

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

Comments

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.