简体   繁体   English

如何使用过滤值从旧的 object 创建新的 object

[英]How to create new object from old one with filtered values

I have an object:我有一个 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.我想创建一个新的 object,但没有包含在现有数组中的值。 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.您可以使用Object.entriesObject.fromEntries以及filter来获得所需的结果。

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)

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

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