Home > OS >  How can i get Array data by using filter method?
How can i get Array data by using filter method?

Time:06-17

I want to filter the data of diaryItems that do not match the key value using the innerstate key value in JavaScript and put it in the answer constant.

I used the code like this, but I didn't get the desired value. How do I fix the code?

this is my code

const innerstate = {
    instar: 'egg',
    feedType: 'feed',  
    feedAmount: 0,              
    inputfeedtime: 0,         
    wormSize: 'third',            
    inputamount: 0, 

}


const  diaryItems = 
[
    
    {diaryItemId: 174, name: "instar"},
    {diaryItemId: 175, name: "recordFeedPeriod"},
    {diaryItemId: 176, name: "feedPeriod"},
    {diaryItemId: 177, name: "feedAmount"},
    {diaryItemId: 178, name: "feedType"},
    {diaryItemId: 195, name: "totalFeedAmount"},
    {diaryItemId: 196, name: "inputfeedtime"},
    {diaryItemId: 197, name: "wormSize"},
    {diaryItemId: 198, name: "inputamount"}
    
]


(expected answer)

const answer = [
    {diaryItemId: 174, name: "instar"},
    {diaryItemId: 178, name: "feedType"},
    {diaryItemId: 177, name: "feedAmount"},
    {diaryItemId: 196, name: "inputfeedtime"},
    {diaryItemId: 197, name: "wormSize"},
    {diaryItemId: 198, name: "inputamount"}

]

I tried this code but it doesn't work

const answer = diaryItems.filter((v) => v.name !== 
Object.keys(innerState))

CodePudding user response:

You were close. You need to check if the keys contain the current entry's name, instead of checking for equality to all keys:

const innerstate = {
    instar: 'egg',
    feedType: 'feed',  
    feedAmount: 0,              
    inputfeedtime: 0,         
    wormSize: 'third',            
    inputamount: 0, 
};

const diaryItems = [        
    {diaryItemId: 174, name: "instar"},
    {diaryItemId: 175, name: "recordFeedPeriod"},
    {diaryItemId: 176, name: "feedPeriod"},
    {diaryItemId: 177, name: "feedAmount"},
    {diaryItemId: 178, name: "feedType"},
    {diaryItemId: 195, name: "totalFeedAmount"},
    {diaryItemId: 196, name: "inputfeedtime"},
    {diaryItemId: 197, name: "wormSize"},
    {diaryItemId: 198, name: "inputamount"}        
];

const keys = Object.keys(innerstate);
const result = diaryItems.filter(({name}) => keys.includes(name));

console.log(result);

CodePudding user response:

You just need to check if the name is in the keys array

const answer = diaryItems.filter((v) =>
    Object.keys(innerstate).includes(v.name)
)
  • Related