Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i get Array data by using filter method?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading