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 ?
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' });
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'
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']);
Related
Let's say I have a blank JavaScript object:
myObject {}
And I also have a variable:
var myChildObject = this.name.split('.')[1];
For the sake of an example, let's say that myChildObject equals "FooBar". Now, I want to add a child object to myObject with the name of "FooBar", only we can't hard code "FooBar". We have to use the variable name myChildObject.
I tried this:
myObject.appendChild(myChildObject);
That doesn't work.
The goal is this:
{
"myObject":{
"FooBar":{
"thing1":25,
"thing2":6
},
.....
}
But I need to build the entire thing dynamically, without the names (other than the root) being known ahead of time.
An object is a "key value" type of thing, a little bit like a Map in Java. have you tried something like this:
let myObject = {};
let myChildObject = "fooBar";
myObject[myChildObject] = {};
This way you have a "fooBar" key for your Object... now you have to decide what you want the value to be for that key.
Objects can only have key value pair. You cannot use one without other. If you don't want to assign a value then simply give undefined. If you don't know the name of the property then you can simply use the array type notation for an object "[]". Refer to code below
var myObject = {};
var myChildObject = this.name.split('.')[1];
myObject[myChildObject] = undefined;
console.log(myObject.hasOwnProperty(myChildObject)); // true
var myObject = {};
var myChildObject = this.name.split('.')[1];
myObject[myChildObject] ={
"thing1":25,
"thing2":6
};
I'd say
for(var key in myChildObject) {
myObject[key] = myChildObject[key]
}
No idea what your question means but myObject["foobar"] might be what you are looking for
I am trying to create a JSON Array:
let someJSON = {};
someJSON["number1"] = "someString";
works. But when I want to set a "Child" to number1 it fails:
someJSON["number1"]["date"] = "19.01.2017";
I tried some things but its not working :(
I need to create the JSON like this because I needs variables as parents
I am trying to create a JSON Array:
let someJSON = {};
someJSON["number1"] = "someString";
That's not a JSON array, that's a JavaScript object.
But when I want to set a "Child" to number1 it fails:
someJSON["number1"]["date"] = "19.01.2017";
That's because you're setting a property on a string primative. That will temporarily promote the string primative to an object, set the property, and then throw away the object, effectively doing nothing.
To make someJSON.number an object, create an object just like you did for someJSON and add properties to it. Or you can do it all at once:
let obj = {
number1: {
date: "19.01.2017"
}
};
If you want "someString" in there somewhere, just put it on another property:
let obj = {
number1: {
str: "someString",
date: "19.01.2017"
}
};
You have to create the "number1" object first. Note that you won't be able to set a string value for "number1" as it is now an object.
let someJSON = {};
someJSON["number1"] = {};
someJSON["number1"]["date"] = "19.01.2017";
It's difficult to explain the case by words, let me give an example:
var myObj = {
'name': 'Umut',
'age' : 34
};
var prop = 'name';
var value = 'Onur';
myObj[name] = value; // This does not work
eval('myObj.' + name) = value; //Bad coding ;)
How can I set a variable property with variable value in a JavaScript object?
myObj[prop] = value;
That should work. You mixed up the name of the variable and its value. But indexing an object with strings to get at its properties works fine in JavaScript.
myObj.name=value
or
myObj['name']=value (Quotes are required)
Both of these are interchangeable.
Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/
You can get the property the same way as you set it.
foo = {
bar: "value"
}
You set the value
foo["bar"] = "baz";
To get the value
foo["bar"]
will return "baz".
You could also create something that would be similar to a value object (vo);
SomeModelClassNameVO.js;
function SomeModelClassNameVO(name,id) {
this.name = name;
this.id = id;
}
Than you can just do;
var someModelClassNameVO = new someModelClassNameVO('name',1);
console.log(someModelClassNameVO.name);
simple as this
myObj.name = value;
When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.
You can access these dictionaries in two ways:
Like an array (e.g. myObj[name]); or
Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.
You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.
You could do the following:
var currentObj = {
name: 'Umut',
age : 34
};
var newValues = {
name: 'Onur',
}
Option 1:
currentObj = Object.assign(currentObj, newValues);
Option 2:
currentObj = {...currentObj, ...newValues};
Option 3:
Object.keys(newValues).forEach(key => {
currentObj[key] = newValues[key];
});
I have an object in a variable var o={};
I want to do something like what .push() method doing in array for my object.
JS code:
// Array:
var ar=[];
ar.push('omid');
ar.push('F');
var got=ar[1];
// above code is standard but not what I'm looking for !
/*-------------------------------------*/
// Object:
var obj={};
/* obj.push('key','value'); // I want do something like this
var got2=obj.getVal('key'); // And this
*/
Is this possible at all ?
var obj = {}
// use this if you are hardcoding the key names
obj.key = 'value'
obj.key // => 'value'
// use this if you have strings with the key names in them
obj['key2'] = 'value'
obj['key2'] // => 'value'
// also use the second method if you have keys with odd names
obj.! = 'value' // => SyntaxError
obj['!'] = 'value' // => OK
Since Object-Literals use a Key->Value model, there is no JS method to "push" a value.
You can either use Dot Notation:
var Obj = {};
Obj.foo = "bar";
console.log(Obj);
Or Bracket Notation:
var Obj = {},
foo = "foo";
Obj[foo] = "bar";
Obj["bar"] = "foo";
console.log(Obj);
Consider reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects, as arming yourself with this knowledge will be invaluable in the future.
Here is some javascript magic that makes it work.
Take a look.
var obj = {};
Object.defineProperty(obj,'push',{
value:function(x,y){
this[x]=y;
}
});
obj.push('name','whattttt'); <<<this works!!!
obj;
//{name:'whattttt'}
obj.name or obj['name']..
//whattttt
The reason i defined .push function using Object.defineProperty because i didn't want it to show up as a property of object. So if you have 3 items in object this would have always been the 4th one. And mess up the loops always. However, using this method. You can make properties hidden but accessible.
Though i don't know why you would use this method when there is already a easy way to do it.
to assign a value do this
obj.variable = 'value';
if value key is number or weird do this...
obj[1] = 'yes';
to access number or weird name you also do that
obj[1];
and finally to assign random keys or key that has been generated in code, not hard coded, than use this form too.
var person= 'him';
obj[him]='hello';
If I have:
var myArray = new Array();
myArray['hello'] = value;
How can I change the key 'hello' to something else?
Something like this would work.
var from = 'hello',
to = 'world',
i, value = myArray[from];
for( i in myArray )
if( i == from ) myArray.splice( i, 1 );
myArray[to] = value;
But is there a native function or a better way to do it?
edit:
Due to the lack of associative arrays in js, what I want to do modify the property name of an object as efficiently as possible.
In JavaScript there is no such thing as associative Array. Objects can be used instead:
var myHash = new Object();
or
var myHash = {};
replace can be done like this:
myHash["from"] = "value";
myHash["to"] = myHash["from"];
delete myHash["from"];
but the preferred way to write it:
myHash.from = "value";
myHash.to = myHash.from;
delete myHash.from;
You can't really "change" the property name, but you can always assign a property value to a new name, and then delete the original one.
myArray['world'] = myArray.hello;
delete myArray.hello;
Also, you're working with an Array instance but using it as a simple object; everything you're doing would work just as well with:
var myArray = {};
The "splice()" you're attempting in the code posted won't work, because it's only for the actual integer-indexed array properties, and not the named properties.
That "delete" doesn't really delete a property really doesn't matter. The "undefined" value is what you get when you check an object for a property and there's no such property.