Add objects to JSON - javascript

I have a JSON that looks like this:
{
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
}
When I add an object to it:
addObj[obj.length] = saveobject;
the previous content gehts replaced.
When I make an array out of it and push the object:
addObj = [loadedJSON];
addObj.push(saveObj);
I get this after the first
[Object]
after the second so fare so good
[Object, Object]
and after the third it gets messed up
[Array(2), Object]
What do I miss?
I hope some one can help with this?
The way I hoped it would look like is this.
[Object, Object, Object, ...and so on]
EDIT
to be More specific
when I add a new Object I load the JSON file in a variable and then I try to add the new Object.
Which works for the first two objects but the third one is added to the first object so that I got this result.
[Array(2), Object]
I dont want it nested like this! But how do I get it like this?
[Object, Object, Object].
EDIT
So eventually you all were right I just mixed up the array when i loaded it the second time every thing is fine now thank for pointing me in the right direction.
on the first time:
var a= [];
var b= {};
b= 'some things';
a.push(b);
and wenn a.length != null
b= 'the rest';
a.push(b);
and now everything is just as expected!

As far as I understand it, this has nothing to do with JSON.
It seems you want to have an array storing successive instances of a given object (that happens to have been encoded in JSON at some point, but for the problem at hand we could not care less).
First, create a sorage array.
Then push each new instance into it.
var storage = []; // your storage array, initially empty
// ....
while (some_guy_wants_to_send_me_something ())
{
var new_object = get_what_the_guy_sent_me_that_happens_to_be_JSON_encoded();
storage.push (new_object);
}
EDIT:
If you use a button:
var storage = []; // your storage array, initially empty
// ....
function add_whatever_object ()
{
var new_object = get_what_the_guy_sent_me_that_happens_to_be_JSON_encoded();
storage.push (new_object);
}
// HTML
<button type="button" onclick='add_whatever_object();'>
I still don't see where the catch is.

check the if it is an array:
Array.isArray(loadedJSON) //true
do this:
loadedJSON.push(saveObj);
if it was not an array push it to an array:
var myarray = [];
myarray.push(loadedJSON);
an then push your other object:
myarray.push(saveObj);
an so on:
myarray.push(otherObj);

I am a little unclear on what you actually want, but based on a little speculation I was able to write the following code for you. I hope this will solve your problem.
var a ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var b ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var c ={
"__v":0,
"_id":"526a7b9c1affd1401d000001",
"ranStr":"azsuC2Ers0qTEcpzS8Jrs1pZ7MQH0goa",
"userId":{
"username":"t",
"_id":"51e11b28418dcfd01f000002"
},
"meta":{
"numberComments":0,
"favs":0,
"views":112
},
"enddate":"2014-01-31T00:00:00.000Z",
"startdate":"2013-10-25T00:00:00.000Z",
"comments":[],
"categories":[],
"fileurl":[],
"telephone":"1234567890"
};
var ObjArr = [];
ObjArr.push(a);
ObjArr.push(b);
ObjArr.push(c);
console.log(ObjArr);
Here is the fiddle to it => http://jsfiddle.net/rB3Un/

Related

Function returning object instead of Array, unable to .Map

I'm parsing an order feed to identify duplicate items bought and group them with a quantity for upload. However, when I try to map the resulting array, it's showing [object Object], which makes me think something's converting the return into an object rather than an array.
The function is as follows:
function compressedOrder (original) {
var compressed = [];
// make a copy of the input array
// first loop goes over every element
for (var i = 0; i < original.length; i++) {
var myCount = 1;
var a = new Object();
// loop over every element in the copy and see if it's the same
for (var w = i+1; w < original.length; w++) {
if (original[w] && original[i]) {
if (original[i].sku == original[w].sku) {
// increase amount of times duplicate is found
myCount++;
delete original[w];
}
}
}
if (original[i]) {
a.sku = original[i].sku;
a.price = original[i].price;
a.qtty = myCount;
compressed.push(a);
}
}
return compressed;
}
And the JS code calling that function is:
contents: compressedOrder(item.lineItems).map(indiv => ({
"id": indiv.sku,
"price": indiv.price,
"quantity": indiv.qtty
}))
The result is:
contents: [ [Object], [Object], [Object], [Object] ]
When I JSON.stringify() the output, I can see that it's pulling the correct info from the function, but I can't figure out how to get the calling function to pull it as an array that can then be mapped rather than as an object.
The correct output, which sits within a much larger feed that gets uploaded, should look like this:
contents:
[{"id":"sku1","price":17.50,"quantity":2},{"id":"sku2","price":27.30,"quantity":3}]
{It's probably something dead simple and obvious, but I've been breaking my head over this (much larger) programme till 4am this morning, so my head's probably not in the right place}
Turns out the code was correct all along, but I was running into a limitation of the console itself. I was able to verify this by simply working with the hard-coded values, and then querying the nested array separately.
Thanks anyway for your help and input everyone.
contents: compressedOrder(item.lineItems).map(indiv => ({
"id": indiv.sku,
"price": indiv.price,
"quantity": indiv.qtty
}))
In the code above the compressedOrder fucntion returns an array of objects where each object has sku, price and qtty attribute.
Further you are using a map on this array and returning an object again which has attributes id, price and quantity.
What do you expect from this.
Not sure what exactly solution you need but I've read your question and the comments, It looks like you need array of arrays as response.
So If I've understood your requirement correctly and you could use lodash then following piece of code might help you:
const _ = require('lodash');
const resp = [{key1:"value1"}, {key2:"value2"}].map(t => _.pairs(t));
console.log(resp);
P.S. It is assumed that compressedOrder response looks like array of objects.

Parsing JSON and loading into array

JSON-https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo
I am trying to take the JSON from the above link and place it in the following format(date,open,high,low,close)...
[
[1277424000000,38.58,38.61,37.97,38.10],
[1277683200000,38.13,38.54,37.79,38.33],
[1277769600000,37.73,37.77,36.33,36.60],
[1277856000000,36.67,36.85,35.72,35.93],
]
The date does not need to be Epoch time.
My code....
$.getJSON('https://www.alphavantage.co/query?
function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo', function(data) {
//Get the time series data
var timeseries = data['Time Series (Daily)']
var ohlcarray = [];
//Loop through each time series and convert it to JSON format
$.each(timeseries, function(key, value) {
var ohlcdata=[];
ohlcdata[0]=value[0];//date
ohlcdata[1]=value[1];//open
ohlcdata[2]=value[2];//high
ohlcdata[3]=value[3];//low
ohlcdata[4]=value[4];//low
ohlcarray.push(ohlcdata);
});
console.log(ohlcarray[0]);//test if worked properly
});
The output....
[undefined, undefined, undefined, undefined, undefined]
value[x] returns undefined. Any ideas on why this happens?
Thanks!
The reason is that in the each loop, the value is not a list but an object. To access it, you'd have to grab it using keys.
ohlcdata[0] = key; //date
ohlcdata[1] = value['1. open']; //open
ohlcdata[2] = value['2. high']; //high
ohlcdata[3] = value['3. low']; //low
ohlcdata[4] = value['4. close']; //low
https://jsfiddle.net/koralarts/7c2fkf93/2/
At this point it is already JSON. As Patrick mentioned, getJSON automatically parses json. You will need to access it with the array bracket notation since there are spaces in the property name.
var timeSeries = data['Time Series (Daily)'];
See ex: https://jsfiddle.net/dz0phhn2/6/

set array as value in json format in Javascript

I want to add array as json value.
Json format is as follows.
json_data = [
'name':'Testing'
'email':'TestEmail'
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
]
How can I set value of 'links' in javascript like that?
I did as follows.
links_array = [];
links_array =['testing','test2'];
json_data.links = links_array;
I wanted to append these two string but couldn't.
Any help would be appreciate.
Assuming that the syntax of your example is correct, you can use the "push" method for arrays.
json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[]
};
json_data.links.push("test1#test.com");
json_data.links.push("test2#test.com");
json_data.links.push("test3#test.com");
You have to make little changes to make it work.
First thing, You have to replace initial square brackets with curly one. By doing this your object will become JSON Literal - a key value pair.
Second thing, You have missed commas after 'name':'Testing' and 'email':'TestEmail'
Below will work perfectly:
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
}
In addition to push as mentioned by #giovannilobitos you can use concat and do it all in one go.
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com'
]
};
var links_array = ['testing','test2'];
json_data.links = json_data.links.concat(links_array);
console.log(json_data.links);
On MDN's array reference you can find a more complete list of how to modify arrays in JavaScript.

Add [DataObject] to exsisting array with var key

Using Cordova, I am trying to get an Object to add to an array. I have this working on node JS using :
theData = {[varkey]:DataObject};
But I can't get this to work the same way within my javascript that cordova runs.
I need to do the following:
var TownName = 'Auckland', var townData = (JSON Data);
theArray = new Array();
theArray[TownName] = townData;
I need to be able to call it back as:
theArray['Auckland']
Which will return (JSON Data)
But it doesn't want to store the data with the key inside the array.
I have also tried:
theArray.TownName = townData;
theArray = [{TownName:townData}];
theArray = {[TownName]:townData}];
Nothing wants to store the data.
Any suggestions?
::EDIT::
data.theData =
"Auckland"[
{
"username":"pndemoname1",
"number":"373456",
"www":"http://373456.pndemoname1",
"icon":"/imgs/pndemoname1.png"
},
{
"username":"pndemoname2",
"number":"373458",
"www":"http://373458.pndemoname2",
"icon":"/imgs/pndemoname2.png"
}
data.town = "Auckland";
townData = new Array();
alert(JSON.stringify(data.theData))//Alerts theData
townData[data.town] = data.theData
alert(townData[townName]) //Alerts undefined
::EDIT2::
Re-defining the array within the function that deals with all of the data, seems to make it work.
As per my answer, the issue was that I assumed javascript vars are global.
Use objects or an array of objects.
A data structure like this:
{
town1: town1Data,
town2: town2Data,
}
Or more common:
[
{
name: "Town 1",
data: {...}
},
{
name: "Town 2",
data: {...}
},
]
For reference:
http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/
I got what you're trying to do, to add property names dynamically to your object is first, by making sure you are using an OBJECT instead of an array, so when you want to store something you will do the following:
var _obj = {}, _something = 'xyz';
_obj[ _something ] = { ... }; // json structure
The problem you're facing is that you want to assign a string value as a key inside your array, which will not work.
However, you can still use the array you defined and do the following:
var _array = new array();
_array.push( { .... } ); // insert json structure
Remember! By using the array you will have to loop through all values every time you want to access your key, just as the best practice to avoid getting into errors.
Good luck.
The issue was that I didn't define the array within the function of where I was trying to add the information to.
I assumed the var was global (Too much PHP)

Getting [object Object] in javascript when I want the value

I've looked at some similar questions, but not seeing exactly what I am doing wrong. I am passing a dict from a .py file to a file that uses javascript.
I know that the javascript file is getting my dict like this:
var numbersFromServer = [{"a": "45", "b": "22", "c": "7"}];
So, when I try something like this:
var numbersFromServer = {{ numbers_list|safe }};
var NumbersViewModel = function() {
var self = this;
theNumbers = [];
for (var key in numbersFromServer) {
theNumbers.push(numbersFromServer[key]);
}
self.num_display = ko.observableArray(theNumbers);
}
ko.applyBindings(new NumbersViewModel());
I am getting [object Object] when I want to get the actual values (45, 22, 7).
Can someone please point me in the right direction?
A fiddle that shows what I am trying to do: http://jsfiddle.net/Znk3q/1/
You have object in array so to get element you shoud
for (var key in numbersFromServer[0]) {
theNumbers.push(numbersFromServer[0][key]);
}
It looks like you have an array containing one object. To access it you need to
for (var key in numbersFromServer[0]) {
theNumbers.push(numbersFromServer[0][key]);
}

Categories

Resources