Create a multidimensional array with a variable key - javascript

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.

Related

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 check if array contains objects

I have array, created from json:
var array = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name2","group":"group2","id":"456", ...},
{"name":"name3","group":"group1","id":"789", ...}];
After I get another array:
var array1 = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name4","group":"group1","id":"987", ...}]
I need to push items from second array into first, but how can I check if first array contains objects from second array?
Each object in array contain more property and some of them are created dynamically so I can't check for example by indexOf(). All solutions that I found works only with simple objects like Int. It will be great if I could check by property "id" for example.
Use find first
var newObj = {"name":"name2","group":"group2","id":"456"};
var value = array.find( s => s.id == newObj.id );
Now push if the value is not found
if ( !value )
{
array.push( newObj )
}
(More generic)you can do this one line using following (which will add all object which is not in array).
array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
var array = [{"name":"name1","group":"group1","id":"123"},
{"name":"name2","group":"group2","id":"456" },
{"name":"name3","group":"group1","id":"789"}];
var array1 = [{"name":"name1","group":"group1","id":"123"},
{"name":"name4","group":"group1","id":"987"}];
array=array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
console.log(array);

key value pair in 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.

How to append an element into a existing array in javascript/jquery

I have an array in javascript
var myArr = {
'textId':'123',
'type':'animal',
'content':'hi dog',
'expires':'27/10/2012'
};
$.each(myArr, function(myArrArrKey, myArrArrValue){
console.log( myArrArrValue );
});
The above console prints following values
123
app
hi app
27/10/2012
Now i am want to append an element to the existing array, i am trying to do like the below one
myArrValue.push({'status':'active'});
The above push throws following error
TypeError: Object #<Object> has no method 'push'
Kindly help me how to append to that existing array element.
I want to print the array like
123
app
hi app
27/10/2012
active
Just do this.
myArr.status = 'active'
or
myArr["status"] = 'active'
Your myArr is an Object not an Array..
push function is available to an Array variable.
this isn't an array, it's an object!
var myArr = {
'textId':'123',
'type':'animal',
'content':'hi dog',
'expires':'27/10/2012'
};
this isn't necessary with jQuery
$.each(myArr, function(myArrArrKey, myArrArrValue){
console.log( myArrArrValue );
});
easier would be
for ( var k in myArr ) {
console.log( myArr[ k ];
}
to add new entries to your "array"
myArr[ 'foo' ] = 'bar'; // this is array notation
or
myArr.foo = 'bar'; // this is object notation
to remove entries from your "array"
delete myArr[ 'foo' ];
or
delete myArr.foo;
FYI:
myArrValue.push({'status':'active'}); wont work. myArrValue isn't the "array" itself and also not an array having the method push.
If it would be an array the result would be, that your latest entry is the whole an object {'status':'active'}
The answer is in the error... you have an object, not an array. Use object notation
myArr.status='active'
Simply use:
myArrValue.status = 'active';
but be aware that what you are using is an object, not an array. Another way to add properties to an object is:
object[key] = value;
this a json object not array push would for an array
for json you do
myObj.NewProp = 123;
Just for the kicks of it..
function push( obj ) {
var prop;
for ( prop in obj ) {
this[prop] = obj[prop];
}
return this;
}
Your object, remember to assing the push method.
var obj = {
a: "a",
b: "b",
push: push
};
And the push:
obj.push({
c: "c",
d: "d"
});
myArr["status"] = 'active';
or
myArr.status ='active';

Categories

Resources