在javascript中返回匹配字符串的数组

时间:2018-06-05 05:51:42

标签: javascript arrays

let data = [{
    name: "John"
    school: ["def","abc"]     
}, 
{
    name: "Lily"
    school: "xyz"
}, {
    name: "Rose"
    school: "abc"
}]

我想要返回有学校的对象==" abc"`。我试过array.includes(" abc)。但它没有给出预期的输出。它只返回哪个学校只有" abc" (输出:Rose-abc)。约翰也应该被包括在内

6 个答案:

答案 0 :(得分:3)

您可以使用



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)

JSFiddle

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);