JavaScript 2 dimension array - javascript

I have 3 arrays
var city = [
['Kaunas', 54.896872,23.892426],
['Vilnius', 54.711136,25.280685],
['Klaipeda', 55.720149,21.131401],
['Utena', 55.536403,25.59494],
];
var lake = [
['Ezeras Bijote', 55.785092,23.062956],
['Ezeras Druksiai', 55.627996,26.565228],
['Ezeras Sartai', 55.804368,25.832863],
['Ezeras Metelys', 54.300299,23.767004],
];
var shop = [
['Kauno Akropolis', 54.891665,23.917744],
['Panorama', 54.709549,25.257454],
['Europa', 54.687514,25.262886],
['Ozas', 54.638628,25.135685],
];
I want add this 3 arrays to 1 array ut don't know how to do this, will very nice if i can call form alements like this bigArr[city][1], bigArr[shop][1],bigArr[lake][1]

Using what you already have:
var bigArr = {"city": city, "lake": lake, "shop": shop};

You may be interested in compact().
Alternatively, just declare it as an object already:
var myObject = {
city: [
....
],
lake: [
....
],
shop: [
....
]
};

You should use Objects instead of Arrays. You can access them by string keys. Create them as a literal:
var coordinates = {
"city": {
Kaunas: [54.896872,23.892426],
Vilnius: [54.711136,25.280685],
Klaipeda: [55.720149,21.131401],
Utena: [55.536403,25.59494]
},
"lake": {
...
},
"shop": {
...
}
}
Then access their properties by using member operators:
Dot notation: coordinates.shop
Bracket notation: coordinates["lake"]
To get the coordinates array for Utena, you might use coordinates.city["Utena"]

You might want to create an object instead of a multidimensional array -
var bigArr = {
"city": {
Kaunas: {
"lat": 54.896872,
"lon": 23.892426
},
Vilnius: {
"lat": 54.711136,
"lon": 25.280685
},
Klaipeda: {
"lat": 55.720149,
"lon": 21.131401
},
Utena: {
"lat": 55.536403,
"lon": 25.59494
}
},
"lake": {
...
},
"shop": {
...
}
}
And then you can use it, like bigArr.city.Kaunas.lat

Related

How can I add an element in object at certain position?

I have this object:
var ages = [{
"getasafieldDetail": {
"id": "xxx",
"asaentrySet": [{
"result": "ON",
"buy": {
"username": "Dis"
},
"offerSet": [{
"createdStr": "2001-08-09 at 11:52 pm",
"value": 5.0
}]
}]
}
}];
and i want to add an element and have an output like this:
var ages = [{
"getasafieldDetail": {
"id": "xxx",
"asaentrySet": [{
"result": "ON",
"buy": {
"username": "Dis"
},
"land": "111", // THIS <<<<------------
"offerSet": [{
"createdStr": "2001-08-09 at 11:52 pm",
"value": 5.0
}]
}]
}
}];
i tried using splice but not works...
ages.splice(ages[0]['getasafieldDetail']['asaentrySet'][0]['offerSet'],0,'"land": "111"');
ages.join();
There is the handy syntax of Destructuring assignments which helps with cutting and reassembling objects.
Edit
#FireFuro99 did point to the ES6/ES2015 spec which explicitly states how to preserve/handle an object's key-order at the object's creation time.
Thus one can say ...
Every JS engine which does support Destructuring assignment has to respect too any object's key order from/at this object's creation time.
const ages = [{
getasafieldDetail: {
id: "xxx",
asaentrySet: [{
result: "ON",
buy: {
username: "Dis",
},
offerSet: [{
createdStr: "2001-08-09 at 11:52 pm",
value: 5.0,
}],
}],
},
}];
const { result, buy, ...rest } = ages[0].getasafieldDetail.asaentrySet[0];
ages[0].getasafieldDetail.asaentrySet[0] = {
result,
buy,
land: "111",
...rest,
};
console.log({ ages });
.as-console-wrapper { min-height: 100%!important; top: 0; }
Splice only works on Arrays.
To make this work, convert your Object to an Array using Object.entries(), then use splice, and then convert it back to an object using Object.fromEntries().
const entrySet = Object.entries(ages[0]['getasafieldDetail']['asaentrySet'][0]);
entrySet.splice(2,0, ["land", "111"]);
ages[0]['getasafieldDetail']['asaentrySet'][0] = Object.fromEntries(entrySet);
This will insert the key-value pair at the the specified position.
The advantage this has over the destructuring assignment is, that you can specify the index, whereas destructuring is pretty hardcoded.
ages[0]["getasafieldDetail"]["asaentrySet"][0].land = '111' will create the key land in the first object in asaentrySet and assign the value 111. Key order is not guaranteed
var ages = [{
"getasafieldDetail": {
"id": "xxx",
"asaentrySet": [{
"result": "ON",
"buy": {
"username": "Dis"
},
"offerSet": [{
"createdStr": "2001-08-09 at 11:52 pm",
"value": 5.0
}]
}]
}
}];
ages[0]["getasafieldDetail"]["asaentrySet"][0].land = '111'
console.log(ages)
When it is an array of objects you could simple, add, passing the position that you want by editing the array like the example below:
let land = {land: 1111}
let ages = [{'a':11},'2', 'wd']
let new =[]
new.push(ages[1])
new.push(land)
ages[1] = new
console.log(ages)
output:
(3) [{…}, Array(2), "wd"]
You get what you want from the array, edit it, and put back in the same position, may it can help.

Javascript:Json Array Data is undefined

I have json array data like this:
var arr= [
{
"id": 1,
"organizationName": "psda",
"Number": "12345"
},
{
"id": 2,
"organizationNameEN": "psda",
"Number": "123456"
}
]
AND after getting this data from json file i will use
var arr1=JSON.stringify(arr)
and then use
var arr2=JSON.parse(arr1)
var i=0;
while(i>=0){
var Data = $scope.documentData = {
"id":arr2[i]["id"],
"organizationNameGE":arr2[i]["organizationName"],
"Number":rawData[i]["Number"]
};
i++}
methods after that i try to get id arr2[i]["id"] and it seems to be undefined ,it throws exception like this Form failure:
Cannot read property 'id' of undefined
What should i change to make my code work?
Method 1
actually...you can't access the arr2[i].["id"] from while loop.
so create a global variable and then use it with this keyword
Method 2
if you are using angular framework.Try using with foreach loop.
var arr= [
{
"id": 1,
"organizationName": "psda",
"Number": "12345"
},
{
"id": 2,
"organizationNameEN": "psda",
"Number": "123456"
}
];
var arr1=JSON.stringify(arr);
var arr2=JSON.parse(arr1);
arr2.forEach(element =>{
alert(element.id);
});

Join JSON attributes

I am working with javascript and I would like to join two JSON file into a single JSON object that contains all the attributes. Right now the two JSON file have separate information but I need to combine them.
Station Information JSON - Example Below:
{
"last_updated":1493307962,
"ttl":10,
"data":{
"stations":[
{
"station_id":"219",
"name":"Central Square - East Boston",
"short_name":"A32036",
"lat":42.37454454514976,
"lon":-71.03837549686432,
"region_id":10,
"rental_methods":[
"KEY",
"CREDITCARD"
],
"capacity":19,
"eightd_has_key_dispenser":false
},
{
"station_id":"220",
"name":"Test 1",
"short_name":"Test 1",
"lat":0,
"lon":0,
"rental_methods":[
"KEY",
"CREDITCARD"
],
"capacity":0,
"eightd_has_key_dispenser":false
}
]
}
}
Station Status JSON - Example Below:
{
"last_updated":1493308075,
"ttl":10,
"data":{
"stations":[
{
"station_id":"219",
"num_bikes_available":7,
"num_bikes_disabled":1,
"num_docks_available":11,
"num_docks_disabled":0,
"is_installed":1,
"is_renting":1,
"is_returning":1,
"last_reported":1493283725,
"eightd_has_available_keys":false
},
{
"station_id":"220",
"num_bikes_available":0,
"num_bikes_disabled":0,
"num_docks_available":0,
"num_docks_disabled":0,
"is_installed":0,
"is_renting":0,
"is_returning":0,
"last_reported":0,
"eightd_has_available_keys":false
}
]
}
}
Specifically, I looked at this post (How to join two json object in javascript, without using JQUERY) but the two JSON files have more complex structure, so I could not make it work.
Any suggestion will be really appreciated.
This code behaves like a join on the 2nd object (but can be extended to perform a full outer join)
It handles conflicts by appending a string _conflict to the key name
I've written this one to get you started but you'll have to customize it to support your exact structure
The combined object isn't a list anymore but has the same indexes as the array.
var obj1 = {
"conflicting_key":1493307962,
"concurrent_key":10,
"data":{
"listOfEvents":[
{
"event_id":219,
"name":"Central Square - East Boston",
"rental_methods":[
"KEY",
"CREDITCARD"
],
"capacity":19
},
{
"event_id":220,
"name":"Test 1",
"lat":0,
"lon":0,
"rental_methods":[
"KEY",
"CREDITCARD"
],
"capacity":0,
"eightd_has_key_dispenser":false
}
]
}
};
var obj2 = {
"conflicting_key":1493308075,
"concurrent_key":10,
"data":{
"listOfEvents":[
{
"event_id":219,
"num_bikes_available":7,
"num_bikes_disabled":1,
"last_reported":1493283725,
"eightd_has_available_keys":false
},
{
"event_id":220,
"num_bikes_available":0,
"num_bikes_disabled":0,
"num_docks_available":0,
"is_returning":0,
"last_reported":0,
"eightd_has_available_keys":false
}
]
}
};
function combine(obj1, obj2) {
var combinedObject = Object.assign({}, obj1);
for(var key in obj2) {
if(typeof obj2[key] !== "object") {
if(obj1[key] !== obj2[key]) {
var keyName = key;
if(key in obj1) {
keyName = keyName + "_conflict";
}
combinedObject[keyName] = obj2[key];
}
} else {
combinedObject[key] = combine(obj1[key], obj2[key]);
}
}
return combinedObject;
}
console.log(combine(obj1, obj2));
I guess you want to merge stations. If both stations arrays are in the same order (as your example shows) you can do it easily this way:
First parse both JSON using JSON.parse and then merge each station object using Object.assign
var obj1 = JSON.parse('your-first-json');
var obj2 = JSON.parse('your-second-json');
obj1.data.stations.forEach(function(item, i) {
Object.assign(item, obj2.data.stations[i])
});
//obj1 will have the obj2 sation data.
If the arrays are not in the same order (same index - same ID) you'll have to perform a lookup by ID before performing the merge.
You could use Array.find for that:
obj1.data.stations.forEach(function(station, i){
var station2 = obj2.data.stations.find(function(item) {
return item.station_id === station.station_id;
});
Object.assign(station, station2);
});
I don't know where you're running this, if in node or in the browser, but there are polyfills for both Object.assign & Array.find in the links I've provided. Also there are many similar functions using jQuery or other similar libraries.
var obj1 = {
"last_updated":1493307962,
"ttl":10,
"data":{
"stations":[
{
"station_id":"219",
"name":"Central Square - East Boston",
"short_name":"A32036",
"lat":42.37454454514976,
"lon":-71.03837549686432,
"region_id":10,
"rental_methods":[
"KEY",
"CREDITCARD"
],
"capacity":19,
"eightd_has_key_dispenser":false
},
{
"station_id":"220",
"name":"Test 1",
"short_name":"Test 1",
"lat":0,
"lon":0,
"rental_methods":[
"KEY",
"CREDITCARD"
],
"capacity":0,
"eightd_has_key_dispenser":false
}
]
}
};
var obj2 = {
"last_updated":1493308075,
"ttl":10,
"data":{
"stations":[
{
"station_id":"219",
"num_bikes_available":7,
"num_bikes_disabled":1,
"num_docks_available":11,
"num_docks_disabled":0,
"is_installed":1,
"is_renting":1,
"is_returning":1,
"last_reported":1493283725,
"eightd_has_available_keys":false
},
{
"station_id":"220",
"num_bikes_available":0,
"num_bikes_disabled":0,
"num_docks_available":0,
"num_docks_disabled":0,
"is_installed":0,
"is_renting":0,
"is_returning":0,
"last_reported":0,
"eightd_has_available_keys":false
}
]
}
};
obj1.data.stations.forEach(function(item, i) {
Object.assign(item, obj2.data.stations[i])
});
console.log(obj1)
I assume you're not interested in the parameters surrounding the stations. You could use this code to get an array of stations with all the information based on station_id
obj1.data.stations.map(el1 => Object.assign({},el1,obj2.data.stations.filter(el2 => el2.station_id === el1.station_id)));
Where obj1 and obj2 are your JSONs.
"[
{
"0": {
"station_id": "219",
"num_bikes_available": 7,
"num_bikes_disabled": 1,
"num_docks_available": 11,
"num_docks_disabled": 0,
"is_installed": 1,
"is_renting": 1,
"is_returning": 1,
"last_reported": 1493283725,
"eightd_has_available_keys": false
},
"station_id": "219",
"name": "Central Square - East Boston",
"short_name": "A32036",
"lat": 42.37454454514976,
"lon": -71.03837549686432,
"region_id": 10,
"rental_methods": [
"KEY",
"CREDITCARD"
],
"capacity": 19,
"eightd_has_key_dispenser": false
},
{
"0": {
"station_id": "220",
"num_bikes_available": 0,
"num_bikes_disabled": 0,
"num_docks_available": 0,
"num_docks_disabled": 0,
"is_installed": 0,
"is_renting": 0,
"is_returning": 0,
"last_reported": 0,
"eightd_has_available_keys": false
},
"station_id": "220",
"name": "Test 1",
"short_name": "Test 1",
"lat": 0,
"lon": 0,
"rental_methods": [
"KEY",
"CREDITCARD"
],
"capacity": 0,
"eightd_has_key_dispenser": false
}
]"

JavaScript Remove Object From Array Based on Child Property

Using vanilla JavaScript (supported by the latest version of Chrome, don't worry about IE) and/or lodash/underscore but no jQuery how can I take this array:
[
{
"id": 1,
"places": {
"city": "boston"
}
},
{
"id": 2,
"places": {
"city": "new york"
}
}
]
...and remove the entire object that has a city of "boston":
[
{
"id": 2,
"places": {
"city": "new york"
}
}
]
Please keep in mind this array could have dozens of entries. Thank you!
http://plnkr.co/edit/JW3zd6A7OcmihM4CTh1D?p=preview
One of the ways you can do this is by using filter. For example:
var dataWithoutBoston = data.filter(function (el) {
return el.places.city !== "boston";
});
And to make it reusable, you can have a function like this:
function removeFromCity(data, name) {
var result = data.filter(function (el) {
return el.places.city !== name;
});
return result;
};

How to parse through a JSON object Map

If I have a JSON Object Map :
var dataItem=[{
"Lucy":{
"id": 456,
"full_name": "GOOBER, ANGELA",
"user_id": "2733245678",
"stin": "2733212346"
},
"Myra":{
"id": 123,
"full_name": "BOB, STEVE",
"user_id": "abc213",
"stin": "9040923411"
}
}]
I want to iterate through this list and access the names (i.e. Lucy, Myra ) and corresponding information
All the loops that I came across looped through the list like this :
var dataItem = [
{"Name":"Nthal","Class":3,"SubjectName":"English "},
{"Name":"Mishal","Class":4,"SubjectName":"Grammer"},
{"Name":"Sanjeev","Class":3,"SubjectName":"Social"},
{"Name":"Michal","Class":5,"SubjectName":"Gk"},
]
for(x in dataItem)
{
alert(dataItem[x].Name);
alert(dataItem[x].Class);
alert(dataItem[x].SubjectName);
}
Thanks in advance
What you have there is not JSON, maybe because you've already parsed it. You have is an array consisting of a single object, with names for its keys. Regardless, I'll show you how to access that data:
var data = dataItem[0];
for(name in data) {
alert(name);
alert(data[name].id);
alert(data[name].full_name);
}
for (var x in dataItem[0]) {
if (dataItem[0].hasOwnProperty(x)) {
console.log(x);
}
}
http://jsfiddle.net/B44LW/
If you want other properties, then you can use the bracket notation:
dataItem[0][x].id

Categories