1

Is it a feasible solution to keep make arrays with _ids from mongodb database in front-end part? Let us suppose that I need to maintain the status of people with their ids . Is it good to associate things like this:

let arr=[];
arr['5bbaea8847910db52c7c3682']='p';
arr['5b9f6a1fd85effbb8acbd1fe']='a';
console.log(arr['5b9f6a1fd85effbb8acbd1fe']);

or Is It better to keep things like this :

 let arr=[];
 arr.push({
     _id:5bbaea8847910db52c7c3682,
     status:'p'
});

I fear if such big ids may lead to memory problems or such things. I have been a C++ programmer previously so it does not appear to be a cool thing to do. Is it OK to do such things in JavaScript ?

4
  • 6
    Your first code is abusing an array as an object. Definitely use an object instead, or an array of objects. Commented Oct 15, 2018 at 7:05
  • See this answer to learn what actually happens when you try to have a string as array index: stackoverflow.com/questions/9526860/… Commented Oct 15, 2018 at 7:13
  • if you just want to save a short key, maybe try using hash function? Commented Oct 15, 2018 at 7:16
  • @George I removed that tag . Commented Oct 15, 2018 at 7:26

3 Answers 3

1

As said above, u can use object of objects:

let data = {};
data[5bbaea8847910db52c7c3682] = {
   status: 'p'
}

Or a map:

let data = new Map();
data.set(5bbaea8847910db52c7c3682, { status: 'p' });
Sign up to request clarification or add additional context in comments.

Comments

0

Better to make arr as an object instead of array. Below is an example of creating new object as well as adding/editing it's property.

let obj = {} // or obj = new Object()
obj['5bbaea8847910db52c7c3682'] = 'p'
obj['5b9f6a1fd85effbb8acbd1fe'] = 'a'
console.log(obj)

To delete certain property, simply use delete keyword:

let obj = {}
obj['5bbaea8847910db52c7c3682'] = 'p'
delete obj['5bbaea8847910db52c7c3682']
console.log(obj)

if the property name is reserved keyword or it's contains a whitespace or special characters, then the way to set/get the property's value it's the same like set/get on array. Other than that, dot notation can be used.

let obj = {}

obj.someProperty = 'old value'
obj['someProperty'] = 'new value'

console.log(obj.someProperty) // 'new value'
console.log(obj['someProperty']) // 'new value'

Comments

0

In this situation, it is better to use an array of objects (as you suggested), or simply an ordinary object:

let ob = {};
ob['5bbaea8847910db52c7c3682'] = 'p';
ob['5b9f6a1fd85effbb8acbd1fe'] = 'a';

console.log(ob['5b9f6a1fd85effbb8acbd1fe']);

Comments

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.