let data = [{
name: "John"
school: ["def","abc"]
},
{
name: "Lily"
school: "xyz"
}, {
name: "Rose"
school: "abc"
}]
我想要返回有学校的对象==" abc"`。我试过array.includes(" abc)。但它没有给出预期的输出。它只返回哪个学校只有" abc" (输出:Rose-abc)。约翰也应该被包括在内
答案 0 :(得分:3)
您可以使用
Array#filter
用于获取仅包含数组中某些项的新数组,
destructuring (assignment)仅获取对象的单个属性
与所需值进行比较,方法是检查school
是否为数组,如果不是数组,则选择Array#includes
进行检查。
var array = [{ name: "John", school: ["def", "abc"] }, { name: "Lily", school: "xyz" }, { name: "Rose", school: "abc" }],
result = array.filter(({ school }) => (Array.isArray(school) ? school : [school]).includes('abc'))
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:2)
arr = [{
name: "John",
school: "abc"
}, {
name: "Lily",
school: "xyz"
}, {
name: "Rose",
school: "abc"
}]
a = arr.filter((x) => {
if (x.school == 'abc')
return x
})
console.log(a)
答案 2 :(得分:1)
arr1 = [];
var arr1= array1.concat(arr2);
var index = arr1.findIndex(x => x.school== "abc");
if ( index != -1 ){
console.log(" found")
}
首先连接两个数组的数组并存储arr1 然后找到arr1的索引,如果找不到该值,则该值为abc 它将返回-1基于此你可以存在值
答案 3 :(得分:1)
var arr = [];
arr.push({ name: "John", school:"abc" });
arr.push({ name: "Lily", school:"xyz" });
arr.push({ name: "Rose", school:"abc" });
var temp = [];
arr.forEach(function(el) {
if(el.school == "abc")
temp.push(el);
});
console.log(temp);
答案 4 :(得分:0)
说你的数组就像,
var arr=[ { name: "John" school:"abc" },
{ name: "Lily" school:"xyz" },
{ name: "Rose" school:"abc" }
]
然后你可以得到像
这样的对象var item = arr.filter((obj)=>obj.school==="abc");
现在,item
将拥有您需要的对象
答案 5 :(得分:0)
@mr ukta,如果我理解得当,它可能对你有帮助。
var students = [
{
name: "John",
school:["abc", "def"]
},
{
name: "John2",
school:"Boom"
},
{
name: "John3",
school:"abc"
},
];
var abcStudents = students.filter(({ school }) => (Array.isArray(school) ? school : [school]).includes('abc'))
console.log(abcStudents);