Home > Software engineering >  How to pass an objects array to a component prop in ReactJS excluding objects whose key-value pairs
How to pass an objects array to a component prop in ReactJS excluding objects whose key-value pairs

Time:04-30

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?

CodePudding user response:

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>

  • Related