I have an object var obj = {key1: "value1", key2: "value2"}; I want to add multiple values or array of values to key1 or key2 e.g
var obj = {key1: "arrayOfValues", key2: "value2"}; is it possible? basically I want to send it to php for process.
You can just define an array for the property:
var obj = {key1: ["val1", "val2", "val3"], key2: "value2"};
Or, assign it after the fact:
var obj = {key2: "value2"};
obj.key1 = ["val1", "val2", "val3"];
You can make objects in two ways.
Dot notation
Bracket notation
Also you can be define values in array with/without initial size.
For scenario one you can do the following in worst case scenario:
var obj = {}
obj.key1 = new Array();
obj.key2 = new Array();
// some codes related to your program
obj.key1.push(value1);
// codes ....
obj.key1.push(value);
// ... same for the rest of values that you want to add to key1 and other key-values
If you want to repeat the above codes in bracket notation, it will be like this
var obj = {}
obj['key1'] = new Array();
obj['key2'] = new Array();
// some codes related to your program
obj['key1'].push(value1);
// codes ....
obj['key1'].push(value);
// ... same for the rest of values that you want to add to key1 and other key-values
With bracket notation, you can use characters e.g 1,3,%, etc. that can't be used with dot notation.
I came across same scenario and after scanning through many resources I found very elegant solution. Using Bracket Notation one can add multiple values to same key
let obj = {}
const demo = (str, objToAdd) => {
if(!obj[str]){
obj[str] = {}
}
const key = Object.keys(objToAdd)[0]
obj[str][key] = Object.values(objToAdd)[0]
}
Here important line is obj[str][key] = Object.values(objToAdd)[0]. This line will help you create object inside same key. obj[str][key] will create object inside object.
to add values call function as below
demo('first', {content: 'content1' } )
demo('first', {content2: 'content3' } )
obj
first: {content: "content1", content2: "content3"}
Hopefully this will help someone.
Related
Let's say I have two arrays which are returned in a response from a REST call. For simplification I defined them hard-coded as keys and subKeys in the following example code.
From these arrays I'd like to create a nested object which, when outputted as a JSON string, looks like this:
Target JSON
{
"key1": {
"subKey1": "someValue"
},
"key2": {
"subKey2": "someValue"
},
"key3": {
"subKey3": "someValue"
}
}
Code sample
var keys = ["key1", "key2", "key3"]; // These come from a REST response
var subKeys = ["subKey1", "subKey2", "subKey3"]; // These come from a REST response
var targetObj = {}
for (const key in keys) {
targetObj[key] = {}
for (const subKey in subKeys) {
targetObj[key][subKey] = "someValue";
}
}
console.log(JSON.stringify(targetObj, null, 2));
While this gives me the correct behavior in my application I have the impression that there might be simpler approaches to achieve the same result, either in "vanilla" JavaScript or ES6? What bothers me here is that I define an empty object in each run of the for loop.
Your code does not produce the example output you said you want. It will put all 3 subkeys under each key, not one per key. Also you end up with numeric keys, not the key names.
var keys = ["key1", "key2", "key3"]; // These come from a REST response
var subKeys = ["subKey1", "subKey2", "subKey3"]; // These come from a REST response
var targetObj = {}
for (let i=0; i<keys.length; i++) {
const key = keys[i];
targetObj[key] = { [subKeys[i]]: "someValue" };
}
console.log(JSON.stringify(targetObj, null, 2));
First you were using "in" instead of "of" in the for-loop, and secondly you were not using the same index to find the subkey.
To avoid creating an empty object you can use this syntax:
{ [variable]: "value" }
This creates the object with the variable value as the key, and a string as the value. Putting the variable name in square brackets tells it to use the variable value rather than its name. Saying { variable: "value" } wouldn't work because the key would be "variable" not the value of variable.
Just use Array.prototype.reduce method:
const keys = ["key1", "key2", "key3"];
const subKeys = ["subKey1", "subKey2", "subKey3"];
const result = keys.reduce((acc, key, index) =>
({ ...acc, [key]: { [subKeys[index]]: 'someValue' } })
, {});
Note, this works only if keys and subKeys arrays are synced and their indexes are consistent with each other.
Applying filters in MongoDb
I need to apply filters in mongoDb in an embedded document so how can I make a query like
Example:
var query = {
_id:userId,
'match.Id':matchId,
'match.userId':userId1
}
now I want to apply filters lets suppose
case 1: my query should be like
var query = {
_id:userId,
'match.Id':matchId,
}
case 2 :
var query = {
_id:userId,
'match.userId':userId1
}
there can be many cases like this
So my question is how can I make this query object in node.js/javascript
My work : I can create multiple key in an object but creating key as below doesn't works
var query={}
query._id:userId // works
query.'match.userId':matchId // error
query.match.userId:matchId //error
tried below code got desired output but it comes with square bracket but type of arr is object
var arr = [];
arr[ 'key3.abc' ] = "value3";
arr[ 'key2.abc' ] = "value3";
console.log(arr)//[ 'key3.abc': 'value3', 'key2.abc': 'value3' ]
desired output:
{'key3.abc': 'value3', 'key2.abc': 'value3'}
Change [] to {}
var obj = {};
obj[ 'key3.abc' ] = "value3";
obj[ 'key2.abc' ] = "value3";
console.log(obj) // { 'key3.abc': 'value3', 'key2.abc': 'value3'}
N.B. We can assign or access a JavaScript object by square ([]) notation when key contains special character e.g. space, dot etc.
Id like to know if theres a way to programmatically create this array in javascript. Id like to have it dynamic also.
var tblObj = {
main1: {
var2: var3,
var3: var4
},
main2: {
var5: var6
}
};
Thanks
If you mean an object (as in your example), and want to use variables as keys, you'll have to split the declaration in multiple lines, and use bracket notation:
var tblObj = { main1: {}, main2: {} };
tblObj.main1[var2] = var3;
tblObj.main1[var3] = var4;
tblObj.main2[var5] = var6;
(Assuming all those variables are already defined.)
Sure, you can define a multi-dimensional array in one line, exactly as you are, just using the [] array notation. {} is for objects.
var multidim = [
[1,2,3],
[4,5,6],
[7,8,9]
];
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamically creating keys in javascript associative array
usually we initialize an array like this:
var ar = ['Hello', 'World'];
And for access to it's values we do:
alert(ar[0]); // Hello
But I want a custom index to assign, ex:
var ar = ['first' => 'Hello', 'second' => 'World'];
and then
alert(ar['first']);
But I can't find how, is there something like this that I could do for assign?
Thank's!
You could use Object instead of Array, you can specify named properties for object
var ar = {
first: 'hello',
second: 'world'
};
alert(ar['first']);
Also you can just assign properties with string keys to your array, this will also work:
var ar = [];
ar['first'] = 'first';
alert(ar['first']);
You need to use an Object.
var obj = {'first': 'hello', 'second': 'world'};
alert(obj.first);
Objects in JavaScript are just property bags (hashtables).
You can:
var ar = {};
ar["name"] = "Dave";
ar["salary"] = "Millions";
alert(ar.name); //Dave
alert(ar["salary"]); //millions
JavaScript allows you to be pretty flexible in how you create these objects.
JavaScript doesn't have associative arrays as such, but object literals:
var obj = {foo:'bar'};
obj.something = 'else';
//or:
obj['foo'] = 'BAR';
JS won't make a fuss if you create named indexes on an array (because the Array object traces back to the Object prototype) but you'll loose all use of Array features (methods like sort, or the magic length property, to name just a few)
just use
var h = new Object(); // or just {}
h['one'] = 1;
h['two'] = 2;
h['three'] = 3;
// show the values stored
for (var k in h) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (h.hasOwnProperty(k)) {
alert('key is: ' + k + ', value is: ' + h[k]);
}
}
You can do this:
var ar = {
'first' :'Hello',
'second' : 'World'
};
As you can see, this is the way you initialize objects in Javascript. Javascript blurs the lines between associative arrays and objects.
You can then access this with:
ar['first']
Or even:
ar.first
Also, you could leave out the quotes in the key initialization, like so:
var ar = {
first :'Hello',
second : 'World'
};
I currently have a problem in deleting entries from an associative array in JS.
I tried this:
myArray['key'] = value;
myArray['key1'] = value1;
...
delete myArray['key'];
But I get following results in my application:
[ undefined, { key1: 'value1', key2: 'value2' }, undefined,
{ key1: 'value1', key2: 'value2' }, undefined, undefined ]
How can I delete the whole entry, key and value? I found the method splice() but I think it uses a different index. I wasn't able to delete the entries I want by passing the key to splice().
It seems you are mixing arrays and objects. Associative arrays should be realized with objects:
myArray = {};
myArray['key'] = value;
myArray['key1'] = value1;
It is a bit confusing though because in your output, the objects don't have key anymore (so it worked), but the array containing those objects as undefined values. I cannot see how
delete myArray['key']; is related to your output and which variable now contains which value (please clarify).
But it looks like you did something like:
var container = new Array(6);
container[1] = myArray;
container[3] = myArray;
This will initialize the array with 6 undefined values (sort of) and then set the second and forth value to something else.
If you want to use that "array" as associative array, you should declare it as object too:
var container = {};
Please post more code if you need a better answer.
Update: Yes, you should declare displayedWidgets as object:
var widgets = {
displayedWidgets: {},
clear: function() {
this.displayedWidgets = {};
},
add: function(widget) {
this.displayedWidgets[widget.id] = widget;
},
addArray: function(newWidgets) {
// note that `each` is only available in newer browsers,
// just loop over the array
for(var i = newWidgets.length; i--; ) {
this.add(newWidgets[i]);
}
},
remove: function(widgetId) {
if (widgetId in this.displayedWidgets) {
delete this.displayedWidgets[widgetId];
}
}
};