Map in map storing - javascript

how can I store map in map in javascript?
var data = {};
data['key'] = {'val1', 'val2'};
And I get an error about wrong id.

You either need an array...
var data = {};
data['key'] = ['val1', 'val2']; // store an Array at data.key
data.key[0]; // 'val1'
...or keys for your values in the object...
var data = {};
data['key'] = {key1:'val1', key2:'val2'}; // store an Object at data.key
data.key.key1; // 'val1'

If you want just an array (a list) in the data map, what patrick dw has is fine.
If you want a map in your data map, you need the following:
var data = {};
data['key'] = {'val1': 'val2'}; // using a colon instead of a comma to create key-value pairing
You can also simplify this using JavaScript object notation:
var data = {};
data.key = {val1: 'val2'};

Related

How to Convert an Array into Object of key value pair

I need to convert an array into object with key values.For Example
var Array = [17.3850, 78.4867]
I need to convert into Object in this manner
var Object = {"lat":17.3850, "lng":78.4867}
Using Array.prototype.map() make an iteration over the array, create an array of Object and finally convert that to an object using Object.assign().
var key = ['lat', 'lng'];
var array = [17.3850, 78.4867]
var obj = Object.assign({}, ...key.map((e, i) => ({[e]: array[i]})))
console.log(obj)
You could map an array with arrays of key/value pairs and create an object with Object.fromEntries.
var array = [17.3850, 78.4867],
keys = ['lat', 'lng'],
object = Object.fromEntries(array.map((v, i) => [keys[i], v]));
console.log(object);
you can use the constructor in JavaScript.
class Location {
constructor(lat, lng) {
this.lat = lat,
this.lng = lng
}
}
var myArray = [17.3850, 78.4867];
var myLocation = new Location(myArray[0], myArray[1]);
myLocation.lat;
myLocation.lng;
Instead of myArray[0] & myArray[1] you can use loop to make it dynamic.

how to store json object in array in javascript var objdata = $.parseJSON(data.d);

var objdata = $.parseJSON(data.d);
//here i am parsing json i have six rows in database (Microsoft SQL server 2008)
So my code is creating separate json object for each row so there is total six object in my variable var objdata how to store objdata in array variable?
You could use .map() method to map the object keys to an array.
var objdata = $.parseJSON(data.d);
var arr = Object.keys(objdata).map(function(k) { return objdata[k] });
Another approach would be to use the Object.entries() method, wich wil return an array containing a [key, value] arrays for each property of the given object.
var objdata = $.parseJSON(data.d);
var arr = Object.entries(objdata);
Or simply use the Object.values() method to get the object properties as an array. (This may not work in some browsers)
var objdata = $.parseJSON(data.d);
var arr = Object.values(objdata);

Push Duplicate key data on key array in javascript

I have this data structure. I have used the underscorejs but could not find way to that like the below structure
var data = [{"5+":2},{"3-5":0},{"1-3":1},{"0.5":0},{"<30":0},{"5+":1},{"3-5":1},{"1-3":0},{"0.5":0},{"<30":0},{"5+":3},{"3-5":0},{"1-3":3},{"0.5":0},{"<30":0}];
var groupArr = [];
##loop through the data##
data.forEach(function(item){
##find the keys ##
var keys = Object.keys(item);
var obj = {};
obj[keys] = [];
##push the data to object keys array##
obj[keys].push(item[keys])
groupArr.push(obj)
})
By using this data structure I want something like this structure
[{"5+":[2,1,3]},{"3-5":[0,1,0]},{"1-3":[1,0,,3]},{"0.5":[0,0,0]},{"<30":[0,0,0]}]
As I have tried everything but could not find the solution any help would be highly appreciated.
The first part converts the list of objects to a single object, where the keys are each of the unique keys from the list of objects and the values for each key are joined as an array:
{
"5+": [2,1,3],
"3-5": [0,1,0]
...
}
Since this is not the format you wanted, the second part converts this object into a list of objects by looping over each key and creating a new object from it.
var data = [{"5+":2},{"3-5":0},{"1-3":1},{"0.5":0},{"<30":0},{"5+":1},{"3-5":1},{"1-3":0},{"0.5":0},{"<30":0},{"5+":3},{"3-5":0},{"1-3":3},{"0.5":0},{"<30":0}];
// create object with all the values joined together in lists.
var map = data
.reduce(function (map, obj) {
var key = Object.keys(obj)[0];
// checks if the key allready exits in the new object.
// If it does we push a new value into the array,
// otherwise we create a new property with a list with one value.
map[key] ?
map[key].push(obj[key]):
map[key] = [obj[key]];
return map;
}, {});
// convert above result to a list with objects.
var newFormat = Object.keys(map)
.map(function (key) {
var obj = {};
obj[key] = map[key];
return obj;
})
console.log(newFormat)

how to get data from an array within an array javascript

Let's say I have an array named derps and then I make an array inside it:
derps[0]=new Array();
how do I get/set data in the newly created array derps[0]?
Simply do this:
derps[0][0] = 'foo';
derps[0][1] = 'bar';
derps[0].push('foobar');
derps[0] = derps[0].concat([5,6,7]);
// Etc, etc.
console.log(derps[0][1]); // 'bar'
console.log(derps[0][2]); // 'foobar'
console.log(derps[0]); // ["foo", "bar", "foobar", "foobar", 5, 6, 7]
Basically, access derps[0] like you'd access any other array, because it is an array.
I'm not going to list All methods you can use on derps[0] ;-)
Also, instead of:
derps[0] = new Array();
You can use the "array literal" notation:
derps[0] = []; // Empty array, or:
derps[0] = ['foo', 'bar', 'foobar']; // <-- With data.
You can create the array with data already in it:
derps[0] = [1, 2, 3];
You can assign values to the array:
derps[0] = new Array();
derps[0][0] = 1;
derps[0][1] = 2;
derps[0][2] = 3;
You can push values to the array:
derps[0] = new Array();
derps[0].push(1);
derps[0].push(2);
derps[0].push(3);
You can push data into the new array:
derps[0].push("some data");
As an aside: you may also use an array literal to create derps[0]:
derps[0] = [];
Easy:
var derps = [];
derps.push([]);
derps[0].push('foo');
derps[0].push('bar');
If you really wish to instantiate the type of the variable before, you can proceed this way (JSFiddle).
var derps = [];
derps[0] = [];
derps[0][0] = "test";
derps[0][1] = "test2";
document.write(derps[0][1]);​
Don't forget to write var if you don't want the variable to be global.

JSON.stringify(object) incorrect

Sorry for my last question being so confusing, I was confused my self, but now I got a proper example:
var obj = {};
obj.entities = [];
obj.entities["player"] = [];
obj.entities["player"]["0"] = [];
obj.entities["player"]["0"]["pos"] = "0,0";
var jsonStr = JSON.stringify(jsonObj);
// {"entities":[]}
console.log(JSON.stringify(obj));
The output of JSON.stringify(obj) is wrong as you can see.
What causes this ?
You're first building an array ([]), then assigning properties to it with non-number keys (player). This is technically possible (as in not causing an error), but it's not what arrays are for.
You should use objects ({}) instead. Also, ["player"] is the same as .player.
var obj = {};
obj.entities = {};
obj.entities.player = []; // array here because you're filling with indices ([0])
obj.entities.player[0] = {}; // object again, because non-indices as keys (`pos`)
obj.entities.player[0].pos = "0,0";
Objects can take any property key. Arrays are a subset of objects, which should only have indices (numbers >= 0) as keys.
Your life would be much easier if you'd define your objects in JSON to begin with:
var obj = {
'entities': [
{'player':{'pos': '0,0'}}
]
};
You're using named array indeces instead of object key/value pairs.
var obj = {};
obj.entities = {};
obj.entities["player"] = {};
obj.entities["player"]["0"] = [];
obj.entities["player"]["pos"] = "0,0";
// {"entities":{"player":{"0":[],"pos":"0,0"}}}
console.log(JSON.stringify(obj));
entities, and entities["player"] and entities["player"]["0"] need to be objects, not arrays.
You're adding properties to these arrays, rather than pushing values onto them. These custom properties are not getting stringified.
The fix is simple:
var obj = {};
obj.entities = {}; // <------------ this is an object now
obj.entities["player"] = {}; // <--------- also an object
obj.entities["player"]["0"] = {}; // <-------- and so on
obj.entities["player"]["0"]["pos"] = "0,0";
I think you have some serious confusions about arrays and objects in javascript. An array ([]) works only with positive integer indexes. In your example you are doing the following:
obj.entities = [];
obj.entities["player"] = [];
You say that obj.entities is an array and then you use player as index. And player is not an integer. So this code makes no sense. On the other hand you could use objects with properties. Those properties can be strings:
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = 'foo bar';
You are confusing objects with arrays. The following code will work.
var obj = {};
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = {};
obj.entities.player[0].pos = "0,0";
The things you went wrong:
An array can have only integer indexes. So it's incorrect writing a["1"] if you intend to use a as an array.
To be correctly serialized, only an object can have named properties, like object.entities.player or object.entities["player"].

Categories

Resources