key value pair in javascript - javascript

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.

Related

Dynamically create a nested JavaScript object with unknown keys

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.

Javascript is empty after filling with data

Javascript array is empty after filling with values
I tried this code:
var browserdata = new Array();
// Fill the array with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata); // This shows an empty array
It should show { "qqq" => "zzz", "zzz" => 1 }
Actual output is [] (empty array).
You need to use Object data type instead of Array. Using object structure, you can assign properties to it and corresponding value for that property to get the desired output as { "qqq" => "zzz", "zzz" => 1 }
var browserdata = {};
// Fill the object with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata);
You can also use the another approach, to assign the property at the time object is declared:
var browserdata = {
'qqq': 'zzz',
'rrr': 1
};
console.log(browserdata);
It will never return empty as there are data in the array, with your code it will return an output
[qqq: "zzz", rrr: 1]
If you want to get an output like { "qqq" => "zzz", "zzz" => 1 } , You should use objects .Objects are nothing but a grouping of data,
for example, consider a student array with different data sets.
here you could define individual data or data sets like
student['name'] = john ;
student['mark'] = 20;
OR
students =[{name : john , mark :20} ,{name : rick, mark :20} ]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://javascript.info/array
If new Array() is called with a single argument which is a number, then it creates an array without items, but with the given length.
It’s rarely used, because square brackets [] are shorter. Also there’s a tricky feature with it lets see.
var arr = new Array(2); // will it create an array of [2] ?
console.log( arr[0] ); // undefined! no elements.
console.log( arr.length ); // length 2
var browserdata = new Array();
browserdata[0] = "zzz";
browserdata[1] = 1;
console.log(browserdata);
console.log(browserdata.length);
That solution works for me. Initializing with {} rather than [] or new Array() works. Thanks.
var browserdata = {};
// Fill the object with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata);
Only the positive integer keys of array object are displayed by default, but the rest of the properties can still be accessed and seen in the Google Chrome console.
var arr = []
arr[1] = 1
arr[-1] = -1
arr[.1] = .1
arr.a = 'a'
arr['b'] = 'b'
console.log( arr ) // [undefined, 1]
console.log( arr.b ) // "b"
console.log( { ...arr } ) // { "1": 1, "-1": -1, "0.1": 0.1, "a": "a", "b": "b" }

Grabbing names of object of out a JSON object in javascript and storing it in an String Array

So the issues that I am currently having is a string manipulation logic issue. My goal is to store the names of JSON objects in a string array. So it will be easier to access the data later on. But the current issue that I am running into is that the output is nothing that I want or understand of how it is getting it. Currently I am looking for the quotes between the object names and returning it to a string using str.substring, and storing it in an index of newArr. The output equals in 4th code snippet. I have also tried putting an underscore before and after the object name in the JSON object, then searching for the underscore. From my testing this will only work with the first name, which will return "foo" in index 0, while the rest of the indexes equal to '"_'. I know there is something wrong with my logic in the function, but I can not pinpoint what it is. Any help would be appreciated
This is the function that is being ran.
exports.jsonObjectToArray = function (objectToTurn){
var oldArr = JSON.stringify(objectToTurn).split(","),
firstIndex,
secondIndex,
newArr = [];
for(let i = 0; i < oldArr.length; i ++){
firstIndex = oldArr[i].indexOf("\"");
secondIndex = oldArr[i].indexOf(firstIndex, "\"");
newArr[i] = oldArr[i].substring(firstIndex, secondIndex);
}
return newArr;
}
When the function is ran oldArr will equal to this value.
[ '{"foo":"',
'"bar":"0"',
'"Mar":"0"',
'"Car":"0"}'
]
And my goal is to return this. Which will be stored in newArr.
[
"foo",
"bar",
"Mar",
"Car"
]
But after the function runs this is what I get returned.
[
'{"',
'bar":"0',
'Mar":"0',
'Car":"0'
]
To get the keys from an object, simply use Object.keys().
Quick example:
var obj = {
foo: '1',
bar: '2',
car: '3'
};
console.log(Object.keys(obj)); // ==> (3) ["foo", "bar", "car"]
let arr = [ '{"foo":"',
'"bar":"0"',
'"Mar":"0"',
'"Car":"0"}'
]
let arr1 = arr.map(el => el.split('"')[1])

how to add many values to one key in javascript object

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.

Create a multidimensional array with a variable key

I have an array:
var arr = Array()
I wish to make this a multidimensional array, but I wish to pass in the keys dynamically.
Is there a way to do this?
p.addArrayKey = function(key){
arr.key.push('something');
}
You have not really explained what you mean by "multidimensional array". Multidimensional means that your elements would need to be accessed via more than one index. Example:
arr[ 3, 4 ] = ...; // tells us that arr is a 2-dimensional array
arr[ 4, 5, 1 ] = ..; //.....3-dimensional array
arr[ key ] = 'something'; // is a one-dimensional array!!
But yes, you can use a key as an index as follows. You cannot use the dot notation because key is a variable. And since you have the index, key, you don't use push but you can assign the value directly:
arr[ key ] = 'something';
So that your method is:
p.addArrayKey = function(key, something){
arr[ key ] = something;
};
And you can call it like so:
p.addArrayKey ( 'mykey', 'something' );
And the output would be:
[mykey: "something"]
WORKING JSFIDDLE DEMO
However if something is the key you want to create in the array:
arr.something = 'initial value'; // or
arr[ 'something' ] = 'initial value'; //
Should work just fine.

Categories

Resources