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.
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);
});
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
}
]"
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;
};
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