繁体   English   中英

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

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

我有一个 object:

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

和数组:

const existing = [3,8]

我想创建一个新的 object,但没有包含在现有数组中的值。 我的意思是这个:

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

求指点!

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

您可以使用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