我有一个数组
myArr = [
{
"root": ["1", "6"],
"element": "Apple"
}, {
"root": ["2", "7"],
"element": "Banana"
}, {
"root": ["3", "8"],
"element": "Orange"
}, {
"root": ["4", "9"],
"element": "WaterMelon"
}, {
"root": ["5"],
"element": "Kiwi"
}
]
myArr = [
{
"root": ["1", "6"],
"element": "Apple"
}, {
"root": ["2", "7"],
"element": "Banana"
}, {
"root": ["3", "8"],
"element": "Orange"
}, {
"root": ["4", "9"],
"element": "WaterMelon"
}, {
"root": ["5"],
"element": "Kiwi"
}
]
只是想知道我是否有一个字符串'3'与上面的根数组之一匹配,并且我想从上面的数组中获取元素,我该如何在javascript中做呢?有什么帮助吗?谢谢
答案 0 :(得分:0)
您可以通过以下方式过滤您的数组+您的根destructing
以检查它是否包含“ 3”:
const s = "3"
const myArr = [{
"root": ["1", "6"],
"element": "Apple"
}, {
"root": ["2", "7"],
"element": "Banana"
}, {
"root": ["3", "8"],
"element": "Orange"
}, {
"root": ["4", "9"],
"element": "WaterMelon"
}, {
"root": ["5"],
"element": "Kiwi"
}];
const res = myArr.filter(({
root
}) => root.includes(s))
console.log(res)
答案 1 :(得分:0)
只需过滤数组即可获取元素:
const myArr = [
{
"root": ["1", "6"],
"element": "Apple"
}, {
"root": ["2", "7"],
"element": "Banana"
}, {
"root": ["3", "8"],
"element": "Orange"
}, {
"root": ["4", "9"],
"element": "WaterMelon"
}, {
"root": ["5"],
"element": "Kiwi"
}
];
const ele = myArr.filter(arr => arr.root.includes("3"));
console.log("Required", ele);
答案 2 :(得分:0)
希望这可以帮助您入门:
myArr.forEach((x)=>{
x.root.forEach((j)=> {
if(j=='3'){console.log( x.element);}
})
})
迭代主数组,然后为每个元素迭代“ root”数组。如果它与“ 3”匹配,则返回主要项目的元素字段
答案 3 :(得分:0)
const myArr = [
{
root: ["1", "6"],
element: "Apple"
},
{
root: ["2", "7"],
element: "Banana"
},
{
root: ["3", "8"],
element: "Orange"
},
{
root: ["4", "9"],
element: "WaterMelon"
},
{
root: ["5"],
element: "Kiwi"
}
];
const stringToFind = "3";
const elemList = myArr
.filter(obj => obj.root.includes(stringToFind))
.map(obj => obj.element);
console.log(elemList);