How can I store value of array in a javascript dictionary? - javascript

I want to store array values in a js dictionary (for each date key, there is an array of objects for that date).
Is this possible? and if not, what is the best way to do so?
this is data (fetched from a json):
[
{
"date":"2015-02-08",
"hour":6,
"mac_address":"0C:3E:9F:60:53:32",
"is_inside":"0"
},
{
"date":"2015-02-08",
"hour":6,
"mac_address":"40:0E:85:52:68:4E",
"is_inside":"0"
},
{
"date":"2015-02-08",
"hour":6,
"mac_address":"60:F8:1D:DB:E4:A0",
"is_inside":"0"
}
]
I tried the following, but it just makes a long value of one string.
for (var i=0; i<data.length; i++){
usersByDay[data[i].date] += data[i];
}
What can I do to make a data structure like so:
{date: [object, object, object], another_date: [object...]}, i.e:
{"2015-02-08": [
{
"date":"2015-02-08",
"hour":6,
"mac_address":"0C:3E:9F:60:53:32",
"is_inside":"0" },
{
"date":"2015-02-08",
"hour":6,
"mac_address":"40:0E:85:52:68:4E",
"is_inside":"0" }]
}

+= doesn’t push values into an array in JavaScript, but push does! You’ll also need to check whether the key exists, and create a new array if it doesn’t.
for (var i = 0; i < data.length; i++) {
var item = data[i];
if (usersByDay[item.date]) {
usersByDay[item.date].push(item);
} else {
usersByDay[item.date] = [item];
}
}
Or, if you like “fanciness”:
for (var i = 0; i < data.length; i++) {
var item = data[i];
(usersByDay[item.date] || (usersByDay[item.date] = [])).push(item);
}

Related

looping thru array list

test = [
[value1],
[value2]
];
for (var i = 0; i < test.length; i++) {
console.log(test[i])
};
I tried this but it only returns value1. I would like to have all values returned so I can use each value.

Dictionary inside array in Javascript

I have certain data sets. Example, A,B and C. There are sets of these values. For example:-
[A:asd, B:ajs, C:aknd],
[A:sdf, B:gss, C:fdss],
[A:ijq, B:cba, C:jqwd]
etc.
Now i want to make a dictionary containing these values as separate dictionaries. For example:-
{
{
A:asd,
B:ajs,
C:aknd
},
{
A:sdf,
B:gss,
C:fdss
},
{
A:ijq,
B:cba,
C:jqwd
}
}
Can someone help me out with this.
I tried doing this but it's not making a dictionary.
for( var i=0; i< n; i++) {
data += {
"A":value1,
"B":value2,
"C":value3
}
}
Any inputs?
This does not make sense in Javascript:
{
{
A:asd,
B:ajs,
C:aknd
},
{
A:sdf,
B:gss,
C:fdss
},
{
A:ijq,
B:cba,
C:jqwd
}
}
If you intend to have an object (dictionary) with integer keys, you could do it like so:
var data = {};
for( var i=0; i< n; i++) {
data[i] = {
"A":value1,
"B":value2,
"C":value3
}
}
Depending a bit on what you're trying to do, an array would likely be a better choice:
var data = [];
for( var i=0; i< n; i++) {
data.push({
"A":value1,
"B":value2,
"C":value3
});
}

Create array based on object properties

I'd like to use an object to configure some settings for an app. My idea is to start with this:
var obj = {
property_one: 3;
property_two: 2;
property_three: 1;
}
And I would like to end up with this:
var array = [
'property_one','property_one','property_one',
'property_two','property_two',
'property_three'
]
My current solution is to do this for each property:
function theConstructor(){
for(i=1; i <= obj.property_one; i++){
this.array.push('property_one');
};
for(i=1; i <= obj.property_two; i++){
this.array.push('property_two');
};
for(i=1; i <= obj.property_two; i++){
this.array.push('property_two');
};
}
But this gets tedious, because I might have many properties, and these might change as the app evolves.
I know I can loop through object's properties like this:
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
array.push(key);
}
}
But this will push the value to the array, not the key (as a string). Any ideas about how I can do this more efficiently?
Try this
function theConstructor(){
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
for(var i=1; i <= obj[key]; i++){
this.array.push(key);
};
}
}
}
Using Array.prototype.reduce():
var obj = {
property_one: 3,
property_two: 2,
property_three: 1
};
var resultArray = Object.keys(obj).reduce(function(result, curItem) {
for (var index = 0; index < obj[curItem]; index++) {
result.push(curItem);
}
return result;
}, []);
document.write(JSON.stringify(resultArray));

How to loop through an array and use the value to try and find an object name

I was writing to see if I can manipulate jquery arrays.
So I have an object:
myobject = {
abc : {
value : 'abc',
template : '<div class="abc"></div>',
},
},
Now what I have is another array that looks like this:
myarray = ["abc", "cde"];
So what I am trying to do is loop through myarray to see if it matches an object in the myobject.
Now I thought you would accomplish this by doing something like this:
for (var i = 0; i < myarray.length; i++) {
if (myobject.myarray[i]) {
// do something
}
}
Now this gives me an error: Uncaught TypeError: Cannot read property '0' of undefined
So clearly this isn't the approach, how can I loop through myarray to see if myobject has an object that matches the name from the myarray array?
The problem within your code is, that myobject.myarray does not exists, so 0 of a non object is not available. Try to check with in:
for (var i = 0; i < myarray.length; i++) {
if (myarray[i] in myobject) {
// do something
}
}
You can treat a javascript object la dictionary.
Documentation
myobject = {
abc: {
value: 'abc',
template: '<div class="abc"></div>',
},
},
myarray = ["abc", "cde"];
for (var i = 0; i < myarray.length; i++) {
console.log(myobject[myarray[i]]);
}
You need to change the object reference from myobject.myarray[i] to myobject[myarray[i]]
var myobject = {
'abc' : {
value : 'abc',
template : '<div class="abc"></div>',
}
};
var myarray = ["abc", "cde"];
for (var i = 0; i < myarray.length; i++) {
if (myobject[myarray[i]]!=undefined) {
console.log(myobject[myarray[i]]);
}
}
You should be able to do the following.
for (var i = 0; i < myarray.length; i++) {
if (myobject.hasOwnProperty(myarray[i])) {
// do something
}
}
You were close with iterating through the array to look for the match, to finish use hasOwnProperty to check if the current place in the array matches any property in myobject
var myobject = {
abc: {
"value": "abc",
"template": "test"
}
}
var myarray = [ "abc", "cde" ];
for (var i = 0; i < myarray.length; i++) {
var thisKey = myarray[i];
if (myobject.hasOwnProperty(thisKey)) {
//match found
}
}
http://jsfiddle.net/jessikwa/obpacbao/3/

JavaScript - Converting URL like string params to an array

I have a string like this:
var str = 'My_Type_1=SSD&My_Value_1=16GB&My_Category_1=Disk Capacity&My_Type_2=Sony
&My_Value_2=PS4&My_Category_2=Console&My_rowOrder=2,1';
The string mostly has 3 parts except the last key:
Part 1 -> My - is a Common Prefix
Part 2 -> Type or Value or Category and it can keep changing
Part 3 -> It's a numeric value binding Part 1, Part 2 and Part 3 like Spreadsheet row.
The last key is always called
My_rowOrder and it's a comma delimeted value. It specifies how to construct the output array.
In the above example, 2,1 means a key value pair of
My_Type_2=Sony&My_Value_2=PS4&My_Category_2=Console should be the first in the output array.
Using JavaScript, I would like to parse the string and create an array out of it, such that the output is:
Array
(
[ 0 ] => Array
(
[Type] => Sony
[Value] => PS4
[Category] => Console
[Row] => 2
)
[ 1 ] => Array
(
[Type] => SSD
[Value] => 16GB
[Category] => Disk Capacity
[Row] => 1
)
)
How can I do this? I am partially able to do it this way:
function StringToArray(string) {
var request = {};
var pairs = string.split('&');
for (var i = 0; i < pairs.length-1; i++) {
var pair = pairs[i].split('=');
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
//I think I am in the right track, but need assistance
}
Your example output uses associative arrays, which JavaScript doesn't have, but you can use an array of objects instead.
This example outputs an array of objects, in the order specified by the rowOrder parameter. It trims the prefix (defined by prefix), and also trims the row number from the end of the key.
This will also work with the parameters in any order - e.g. you can mix them and it will parse as necessary, and the rowOrder parameter can appear anywhere in the string (doesn't have to be at the end).
Demo
function StringToArray(string) {
var prefix = 'My_'; // set the prefix
var output = [], request = [];
var pairs = string.split('&');
var order;
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if (pair[0].replace(prefix, '') == 'rowOrder') {
order = pair[1];
} else {
var key = decodeURIComponent(pair[0]);
var pos = key.lastIndexOf('_');
var trimmedKey = key.substring(0, pos).replace(prefix, '');
var row = key.substring(pos + 1);
var value = decodeURIComponent(pair[1]);
var found = false;
for (var j = 0; j < output.length; j++) {
if (output[j].Row == row) {
output[j][trimmedKey] = value;
found = true;
}
}
if (!found) {
var obj = { 'Row': row };
obj[trimmedKey] = value;
output.push(obj);
}
}
}
// do the ordering based on the rowOrder parameter
var orderList = order.split(",");
for(var k=0; k<orderList.length; k++){
for(var l=0; l<output.length; l++){
if(output[l].Row == orderList[k]){
request.push(output[l]);
break;
}
}
}
return request;
}
Outputs an array of objects in the order specified by the My_rowOrder parameter:
[
{
Row: "2",
Type: "Sony",
Value: "PS4",
Category: "Console"
},
{
Row: "1",
Type: "SSD",
Value: "16GB",
Category: "Disk Capacity"
}
]
This may works for you...
<script>
var data = "My_Type_2=Sony&My_Value_2=PS4&My_Category_2=Console";
var array = new Array();
alert(JSON.stringify(URLToArray(data)));
function URLToArray(url) {
var request = {};
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return request;
}
</script>
Try this:
function StringToArray(string) {
var request = [[],[]];
var pairs = string.split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
request[pair[0].slice(-1)-1][decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
//console.log(request)
}

Categories