![](/img/trans.png)
[英]How to filter array of object based on another array values using javascript?
[英]How to filter object based on array items using javaScript?
我遇到了這個問題,我的目標是過濾objectOfProductsById並根據條件刪除所有id,例如,如果objectOfProductsById不包含來自arrOfIds的id,我想刪除objectOfProductsById中的數據。 我如何使用 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)
可能是這樣的:
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)
不確定我是否完全理解這個問題,但是如果您嘗試將其 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
. 然后,您可以將這些合並到一個 object 中以獲得您的結果。 這是一個 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);
如果您可以使用 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);
parseInt()
if (!arrOfIds.includes(parseInt(key))) {
delete objectOfProductsById[key]
}
objectOfProductsById
console.log(objectOfProductsById)
如果您想返回 object,請使用Ben Stephens的答案,如果您想返回 ID,請使用我的答案。
使用數組過濾方法。 filter()方法創建一個數組,其中填充了所有通過測試的數組元素(作為函數提供)。
注意:對於沒有值的數組元素, filter()不會執行 function。 注意: filter()不會改變原始數組。
以下將返回一個字符串數組。
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.