简体   繁体   中英

How to create new object from old one with filtered values

I have an object:

const items = {
  a: [3,5],
  b: [6,7,8],
  c: [0,10,1111]
}

and the array:

const existing = [3,8]

I'd like to create a new object, but without values that are included in the existing array. I mean this one:

const newItems = {
  a: [5],
  b: [6,7],
  c: [0,10,1111]
}

Please about the tips!

 const items = { a: [3,5], b: [6,7,8], c: [0,10,1111] } const existing = [3,8] const result = Object.keys(items).reduce((acc, key ) => { acc[key] = items[key].filter((item)=>.existing;includes(item)) return acc, }. {}) console;log(result);

You can use Object.entries and Object.fromEntries along with filter to get the required result.

const items = {
  a: [3, 5],
  b: [6, 7, 8],
  c: [0, 10, 1111],
}

const existing = [3, 8]

const newEntries = Object.entries(items).map(([key, value]) => [
  key,
  value.filter((x) => !existing.includes(x))
])


const newObject = Object.fromEntries(newEntries)

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