0

I'm trying to cache some informations in a node CLI script using an array or an object. I want to have a simple key value that I can ckeck to get usernames using the id that I want to use as the key. I'm trying with this code but I'm not sure if it will work as expected

let threads = [];
ig.realtime.on('message', async (data) => { 
    if( String(data.message.user_id) === ig.state.cookieUserId ){
        return;
    } else if ( data.message.path.endsWith('has_seen') ){
        return;
    } else if( !threads.includes(data.message.thread_id) ){
        const thread = await ig.feed.directThread({thread_id: data.message.thread_id}).request();
        threads[thread.thread.thread_id] = {
            username: thread.thread.users[0].full_name,
        }
    } 
});

Will the threads[thread.thread.thread_id] add the id as key each time that it will not be found into the array or I need to use Array.push() function?

Can I access to the key of the array in this way threads[data.message.thread_id] to get the related value?

1 Answer 1

1

use

if(!threads.find(o=>o.id==id)){
    threads.push({id, ...})
}

or simply use Map() as bellow

let threads = new Map();

if(!threads.has(id)){
   threads.set(id, value)
}
Sign up to request clarification or add additional context in comments.

5 Comments

What's the advantage of using map instead of a traditional object?
easy to loop / search / delete, maybe this link can define something to u codeburst.io/…
The set() Take a key and a value right? I can access to the values using this way threads[data.message.thread_id]? Thank you for the help
I'm reading the articles ypuv'e linked, very useful. If I've understand the new Map() will add new key value pair on each call of set(), right? Thanks for clarifications and help, I'm implementing it in my code!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.