简体   繁体   中英

JavaScript: How to filter array by values nested in object 2 level deep

I have an array of objects.

Within each object of the array, there can be multiple "Book" objects, all with dynamic keys. I want the objects with at least one "Book" object that is new.

For example:

const arr = [
  {
    id: '123',
    book1242: {isNew: true},
    book9023: {isNew: false},
  },
  {
    id: '123',
    book0374: {isNew: false},
    book9423: {isNew: false},
  },
  {
    id: '123',
    book8423: {isNew: false},
    book9023: {isNew: false},
  },
  {
    id: '123',
    book6534: {isNew: true},
    book9313: {isNew: false},
  },
]

So my filtered array will consist of the first and last element of the original array

Expected filtered array

const arr = [
  {
    id: '123',
    book1242: {isNew: true},
    book9023: {isNew: false},
  },
  {
    id: '123',
    book6534: {isNew: true},
    book9313: {isNew: false},
  },
]

I have tried using filter and map , but I get to the point where I have to loop through and check which book is new and I'm not sure how to return that object within the filter.

It sounds like you want something like this:

arr.filter((o) => Object.values(o).some((b) => b.isNew))

Will your array only ever have keys that are id and bookwxyz ? If not you may need to do some checking on the values to make sure they aren't undefined

You could also explicitly check the key using Object.entries and a regular expression:

arr.filter((o) => Object.entries(o).some(([key, value]) => /book\d{4}/.test(key) && value.isNew))

You can use Array#some with Object.values .

 const arr = [ { id: '123', book1242: {isNew: true}, book9023: {isNew: false}, }, { id: '123', book0374: {isNew: false}, book9423: {isNew: false}, }, { id: '123', book8423: {isNew: false}, book9023: {isNew: false}, }, { id: '123', book6534: {isNew: true}, book9313: {isNew: false}, }, ]; const res = arr.filter(obj=>Object.values(obj).some(({isNew})=>isNew)); console.log(res);

 const arr=[{id:"123",book1242:{isNew:,0}:book9023:{isNew,:1}},{id:"123":book0374,{isNew::1},book9423:{isNew,:1}}:{id,"123":book8423:{isNew,:1},book9023:{isNew:,1}}:{id:"123";book6534.{isNew,.0}.book9313,{isNew..1}}]; const res = arr.filter(obj => { for(const [key, val] of Object.entries(obj)){ if(key.substring(0,4) === 'book' && val.isNew === true){ return obj } } }) console.log(res)

 let sorted =[]
  arr.forEach((el, i) => {
         let obj_values = Object.values(el);
         obj_values = obj_values.filter((elem) => typeof elem == 'object' && elem.isNew == true);
if(obj_values.length) sorted.push(arr[i])
     })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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