在 ReactJS 專案中,我有以下物件陣列:
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
}
]
我將上述陣列傳遞給一個道具,如下所示:
<Component
Array={arr}
/>
問題
我不想傳遞任何鍵“b”為空字串的物件(如示例中的第二個物件)。
有什么方法可以將其余物件作為陣列傳遞,而沒有鍵“b”為空字串的物件?
uj5u.com熱心網友回復:
您可以將過濾后的陣列傳遞給不包含key2空字串的物件的組件:
<Component
Array={arr.filter(({key2}) => key2 !== "")}
/>
反應示例如下:
顯示代碼片段
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/468891.html
標籤:javascript 数组 反应 json 目的
下一篇:React無法決議字串物件
