Nightcrawler
Nightcrawler

Reputation: 1081

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. How I can achieve this result using ES6 syntax?

   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)

Upvotes: 0

Views: 51

Answers (5)

Nick Parsons
Nick Parsons

Reputation: 50954

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. This is an O(n) solution (where n is the size of your array of ids):

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():

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

Upvotes: 1

Nejat Njono
Nejat Njono

Reputation: 734

Use Ben Stephens answer if you want to return an object, use mine if you want to return IDs.

Use Array filter methods. The filter() method creates an array filled with all array elements that pass a test (provided as a function).

Note: filter() does not execute the function for array elements without values. Note: filter() does not change the original array.

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)

Upvotes: 0

Onur Özkır
Onur Özkır

Reputation: 555

  1. ForEach returns the key values ​​of the function as strings, so it does not satisfy the if condition. You should use parseInt() for this
if (!arrOfIds.includes(parseInt(key))) {
            delete objectOfProductsById[key]
        }
  1. Since you are using a foreach function, you can only manipulate the variable with scope. at the end of the process you should print the console objectOfProductsById
    console.log(objectOfProductsById)

Upvotes: 0

Abe Mused
Abe Mused

Reputation: 65

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:


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

Upvotes: 1

Ben Stephens
Ben Stephens

Reputation: 3371

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)

Upvotes: 1

Related Questions