简体   繁体   English

如何使用 javaScript 基于数组项过滤 object?

[英]How to filter object based on array items using javaScript?

I have encountered this problem, My aim is to filter objectOfProductsById and remove all id's based on condition, for example, if objectOfProductsById doesn't contain id's from arrOfIds i want to remove data inside objectOfProductsById.我遇到了这个问题,我的目标是过滤objectOfProductsById并根据条件删除所有id,例如,如果objectOfProductsById不包含来自arrOfIds的id,我想删除objectOfProductsById中的数据。 How I can achieve this result using ES6 syntax?我如何使用 ES6 语法来实现这个结果?

 let arrOfIds = [2233, 1235, 4455] let objectOfProductsById = { 2233: { productName: 'simple product' }, 2211: { productName: 'simple product2' }, 1111: { productName: 'simple product2' }, } let newObj = Object.entries(objectOfProductsById).forEach(([key, value]) => { if (.arrOfIds.includes(key)) { delete objectOfProductsById[key] } }) console.log(newObj)

Possibly something like:可能是这样的:

 let arrOfIds = [2233, 1235, 4455] let objectOfProductsById = { 2233: { productName: 'simple product' }, 2211: { productName: 'simple product2' }, 1111: { productName: 'simple product2' }, } let newObj = Object.fromEntries( Object.entries(objectOfProductsById).filter(([key]) => arrOfIds.includes(+key)) ) console.log(newObj)

Not sure I completely understand the question, but if you're trying to copy the objectOfProductsById that have their IDs in arrOfIds into newObj , I would do it like this:不确定我是否完全理解这个问题,但是如果您尝试将其 ID 在arrOfIds中的newObj objectOfProductsById ,我会这样做:


let newObj = Object.entries(objectOfProductsById)
                      .filter(([key]) => {arrOfIds.includes(key)})

If you want to go for a more scalable approach, you can iterate the ids and filter out any that aren't in your object, and then map each id to an object with its corresponding object from your objectOfProductsById . If you want to go for a more scalable approach, you can iterate the ids and filter out any that aren't in your object, and then map each id to an object with its corresponding object from your objectOfProductsById . You can then merge these into one object to get your result.然后,您可以将这些合并到一个 object 中以获得您的结果。 This is an O(n) solution (where n is the size of your array of ids):这是一个 O(n) 解决方案(其中n是您的 id 数组的大小):

 const arrOfIds = [2233, 1235, 4455]; const obj = { 2233: { productName: 'simple product' }, 2211: { productName: 'simple product2' }, 1111: { productName: 'simple product2' }, } const newObj = Object.assign({}, ...arrOfIds.filter(id => id in obj).map(id => ({[id]: obj[id]})) ); console.log(newObj);

If you can use features beyond ES6, then you can use Object.fromEntries() introduced in ES10 instead of Object.assign() :如果您可以使用 ES6 之外的功能,那么您可以使用 ES10 中引入的 Object.fromEntries( Object.fromEntries()代替Object.assign()

 const arrOfIds = [2233, 1235, 4455]; const obj = { 2233: { productName: 'simple product' }, 2211: { productName: 'simple product2' }, 1111: { productName: 'simple product2' }, } const newObj = Object.fromEntries(arrOfIds.filter(id => id in obj).map(id => [id, obj[id]]) ); console.log(newObj);

  1. ForEach returns the key values of the function as strings, so it does not satisfy the if condition. ForEach 将 function 的键值作为字符串返回,因此不满足 if 条件。 You should use parseInt() for this您应该为此使用parseInt()
if (!arrOfIds.includes(parseInt(key))) {
            delete objectOfProductsById[key]
        }
  1. Since you are using a foreach function, you can only manipulate the variable with scope.由于您使用的是 foreach function,因此您只能使用 scope 操作变量。 at the end of the process you should print the console objectOfProductsById在该过程结束时,您应该打印控制台objectOfProductsById
    console.log(objectOfProductsById)

Use Ben Stephens answer if you want to return an object, use mine if you want to return IDs.如果您想返回 object,请使用Ben Stephens的答案,如果您想返回 ID,请使用我的答案。

Use Array filter methods.使用数组过滤方法。 The filter() method creates an array filled with all array elements that pass a test (provided as a function). filter()方法创建一个数组,其中填充了所有通过测试的数组元素(作为函数提供)。

Note: filter() does not execute the function for array elements without values.注意:对于没有值的数组元素, filter()不会执行 function。 Note: filter() does not change the original array.注意: filter()不会改变原始数组。

The following will return an array of strings.以下将返回一个字符串数组。

let arrOfIds = [2233, 1235, 4455]

let objectOfProductsById = {
    2233: {
        productName: 'simple product'
    },
    2211: {
        productName: 'simple product2'
    },

    1111: {
        productName: 'simple product2'
    },
}

let newObj = Object.keys(objectOfProductsById).filter(key => {
    return arrOfIds.includes(parseInt(key))
})

console.log(newObj)

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

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