我想要實作的是:
- 查找陣列中的文本物件是否為空。
- 如果來自 no1 的條件匹配,則回傳位于該物件頂層的 id 值。
https://codesandbox.io/s/cranky-swirles-gb6ct?file=/src/App.js:410-412 在代碼沙箱的示例中,我添加了兩個物件,帶有空文本字串,在這種情況下,我希望回傳一個字串陣列(結果 = ['662e4120', '782h7a9x'])
我能夠找到空值,但是我不確定如何從上層范圍回傳物件。
如果您無法訪問 codeSandbox,請在下面附上代碼段:
const array = [
{
id: "5548d3c2",
state: {
properties: [
{
text: "text",
key: "fs5a"
}
]
}
},
{
id: "662e4120",
state: {
properties: [
{
text: "",
key: "m03n"
}
]
}
},
{
id: "782h7a9x",
state: {
properties: [
{
text: "",
key: "y5x1"
}
]
}
}];
const findItem = () => {
return array
.map((item) => item.state)
.map((item) => item.properties)
.flat()
.filter((item) => item.text === "");
};
uj5u.com熱心網友回復:
嘗試做這樣的事情https://codesandbox.io/s/jovial-mcnulty-2fwh4
export default function App() {
const array = [
{
id: "5548d3c2",
state: {
properties: [
{
text: "text",
key: "fs5a"
}
]
}
},
{
id: "662e4120",
state: {
properties: [
{
text: "",
key: "m03n"
}
]
}
},
{
id: "782h7a9x",
state: {
properties: [
{
text: "",
key: "y5x1"
}
]
}
}
];
const findItem = () => {
return array.filter(obj=>obj.state.properties[0].text==="").map(obj=>obj.id)
};
console.log(findItem());
return <div className="App"></div>;
}
在這里,我們根據謂詞對原始陣列進行過濾obj=>obj.state.properties[0].text===""。這基本上得到了滿足這個謂詞函式的陣列的所有元素。在此之后,我們只是在結果上應用 map 以獲得滿足此謂詞函式的陣列元素的 id。
uj5u.com熱心網友回復:
要獲取包含物件 ID 且沒有文本的陣列,您必須更改順序或迭代。
- .filter() 帶有空文本欄位的元素的陣列。
- .map() 將剩余元素映射到您想要的值
在映射或過濾時,您不能只進行一層,而可以根據需要進行任意深度。由于“屬性”包含一個陣列,并且您希望使用索引陣列 [0] 訪問它的第一個元素(因為您所做的 flat() 是多余的)
const findItem = () => {
return array
.filter(item => item.state.properties[0].text === "") // (2) [{…}, {…}] the original items with no text
.map(item => item.id) // ['662e4120', '782h7a9x']
};
(代碼也可以像代碼段一樣嵌入,可以直接運行)
const array = [
{
id: "5548d3c2",
state: {
properties: [
{
text: "text",
key: "fs5a"
}
]
}
},
{
id: "662e4120",
state: {
properties: [
{
text: "",
key: "m03n"
}
]
}
},
{
id: "782h7a9x",
state: {
properties: [
{
text: "",
key: "y5x1"
}
]
}
}];
const findItem = () => {
return array
.filter(item => item.state.properties[0].text === "") // (2) [{…}, {…}] the original items with no text
.map(item => item.id) // ['662e4120', '782h7a9x']
};
console.log(findItem())
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/339090.html
標籤:javascript 数组 目的 多维数组 过滤
下一篇:C 輸出陣列函式
