简体   繁体   English

如何过滤数组object中的数组?

[英]How do i filter the array in object of array?

How do i filter roles in this array to return true when "Admin" is found?当找到"Admin"时,如何过滤此数组中的roles以返回 true?

const array = [{
    "country": "all",
    "roles": [
        "Normal",
        "Admin",
    ]
}]

Use .filter() and .includes() :使用.filter().includes()

const admins = array.filter((u) => u.roles.includes("Admin"))

1.Did u mean to return a boolean overall? 1.你是想退boolean吗?

In Js es6 , you could use .some() MDN web docsJs es6中,你可以使用.some() MDN web docs

it's nice and simple:)很好很简单:)

 const array = [{ "country": "all", "roles": [ "Normal", "Admin", ] }, { "country": "test", "roles": [ "Normal" ] }] const result = array.some(o => Boolean(o.roles.some(role => role === 'Admin'))) console.log(result) // return true

2.Or, did u mean that it returns a new array in which each roles become a boolean depending on having 'Admin' or not? 2.或者,您的意思是它返回一个new array ,其中每个角色根据是否具有“管理员”变为 boolean?

If it is, .some() works as well:)如果是, .some()也可以:)

Try below:尝试以下:

 const array = [{ "country": "all", "roles": [ "Normal", "Admin", ] }, { "country": "test", "roles": [ "Normal" ] }] const result = array.reduce((acc, curr, index) => { const item = Object.assign({}, curr, { roles: curr.roles.some(o => o === 'Admin') }) acc.push(item) return acc }, []) console.log(result) // return true

or if it filter an array, my answer is the same as Tobias':)或者如果它过滤一个数组,我的答案和 Tobias 一样:)

  const array = [{
   "country": "all",
   "roles": [
    "Normal",
    "Admin",
   ]
   }]

    const val = array.map((a) => a.roles.includes('Admin'))
                  
    console.log(val) //return true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM