How can i add an json into an index on my json - javascript

I'm trying to insert some more data into an json I'm retrieving from an database, I need to insert it into an already existing json index.
I've already tried to do an json[0].push(otherjson), but I don't understand how to do this.
var devices = JSON.parse(result);
//devices = [{ {id:1, name:'device1'},{id:2, name:'device2'} }]
devices[0].push({"data1":{"temp":"100", "humid":"12"}});

var devices = [ {id:1, name:'device1'}, {id:2, name:'device2'} ];
devices[0]['data1'] = [{"temp":"100", "humid":"12"}];

You can push new elements into an array. Note that devices[0] is not an array rather it's an object.
And you can add new key and corresponding values into an object in this way
object.new_key = new_value
hence your code will be devices[0]."data1" = [{"temp":"100", "humid":"12"}];

Related

javascript - How to split JSON array into separate arrays for DataTables

I am trying to take a JSON array like this
[Alex, James, John]
and create seperate JSON arrays for them like this
[[Alex], [James], [John]]
So I can then insert the JSON payload into a datatable using Datatables.JS
So far I have this
var data = json;
while (data.length) {
console.log(data.splice(0, 1));
}
return data;
Now this splits the JSON into 3 seperate arrays but when I try to use the data variable in the datatables.JS, it complains that is not in the proper format because it is
[Alex]
[James]
[John]
in the console.
I want to combine them into the JSON payload described above so I can insert it into the datatable.
I think using the map method helps in your case!
If this is your JSON data = "["Alex","James","John"]". You can parse it with JSON.parse("["Alex","James","John"]"), this would results you an array object as ['Alex', 'James', 'John']
let personArray = ['Alex', 'James', 'John'];
let resultantArray = personArray.map(name => [name]);
console.log(resultantArray);
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
I would do this:
let ar = ["Alex", "James", "John"]
let ar1 = ar.slice(1)
let ar2 = ar.splice(0, 1)
console.log([ar2, ar1])
This solution assumes that you have already parsed your json into a Javascript array

Insert objects without matching column name

This is probably a silly question, but I am new to node and postgresql, so I am struggling.
I am trying to use pgp.helpers.insert to insert multiple objects into the database, as the example bellow:
users = [{mycolumn:{name: 'John', age:23}}, {mycolumn:{name: 'Mike', age: 30}}];
query = pgp.helpers.insert(users, ['mycolumn:json'], 'mytable');
// insert into "mytable"("mycolumn") values('{"name":"John","age":23}'),('{"name":"Mike","age":30}')
The code above inserts into mytable 2 rows with mycolumn as a jsonb.
But I am trying to insert straight into mycolumn the values inside an array of objects, without wrapping my original object, such as:
users = [{name: 'John', age:23}, {name: 'Mike', age: 30}];
query = pgp.helpers.insert(users, ['mycolumn:json'], 'mytable');
// Error: Property 'mycolumn' doesn't exist.
Of course it doesn't work, since the object doesn't contain a mycolumn attribute. But I think it is not elegant to iterate in my array wrapping the original object with the column name, specially since I am working with millions of rows (working in batches, of course).
Thanks in advance.
You can use the following definition for your column, as per the Column syntax:
{
name: 'mycolumn',
init: c => c.source // use the source object itself
}
i.e.
const cs = new pgp.helpers.ColumnSet([
{
name: 'mycolumn',
init: c => c.source
}
], {table: 'mytable'});
and then use it:
const query = pgp.helpers.insert(users, cs);
Note that we are not specifying the modifier - mod: ':json', because we are returning an object from init, and objects are formatted as JSON by default.

JQuery string to Object Array

I call the function tabulator() with these params.
$("#tableObj").tabulator("addRow", {id:1, Name:"John", Age:"20"}, true);
I want to pass the Array elements name dynamically,
read from a Json ( '{id:1, Name:"John", Age:"20"}' ).
I mean that column names will change.
Ex : {id:1, Company:"myComp", Address:"myaddress"}
How can I create theses objs from Strings or JSon text?
You could use JSON.parse but be aware that id:1, Name:"John", Age:"20" is NOT valid JSON. The keys must be wrapped in quotes, otherwise it will produce an error.
var str = '{"id":1, "Name":"John", "Age":"20"}';
var obj = JSON.parse(str);
$("#tableObj").tabulator("addRow", obj, true);

How can I stringify a Javascript array to store in localStorage

I am trying to store an array in localStorage (HTML5) which needs to be a string, but enable direct access to objects I store in the array by defining the index. When I try to JSON.stringify I just get [] which doesn't store the array of objects in localStorage.
var mylist = [];
mylist["mykey1"] = {id: "1", title: "First"};
mylist["mykey2"] = {id: "2", title: "Second"};
localStorage.setItem("mylist", JSON.stringify(mylist)); // stores [] only - uggh!
var mylist2 = JSON.parse(localStorage.getItem("mylist"));
document.write(JSON.stringify(mylist2["mykey1"])); // want it to display: {"id": "1", "title": "First"}
I think I solved it just by changing the mylist var from [] array to {} object.
var mylist = {};
You've created an array and you're trying to use it like an associative array or map
What's actually happening is when you type
mylist["mykey1"] = {id: "1", title: "First"}
It's trying to get a list element at index "mykey1", which is being ignored by the JSON parser. This is probably due to the fact that it cannot determine an integer index into your list for mykey1, or it's conversion to a number is too large.
You'll notice that if you do this:
mylist[1] = {id: "1", title: "First"}
Your JSON string will be "[null,{id: "1", title: "First"}]", as you haven't specified a 0th index element, but you have set the 1st index element.
Because you are using an array as a normal object.
Change var mylist = []; to var mylist = {};, then thing will be work.
Check the demo.

How to take json response in an array

I am making a ajax request in jquery and in return getting the response but not as an array.
{"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}}
{"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}}
I want to merge the above two response and create an array something like this :
{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"},{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}
Please suggest how to do it. I want to take it in array and store it locally may be in config varaible get:[] and then access somewhat like config.get[data["seriesId"]].
you need to convert your response into an array of objects:
var response = [
{"ErrorCode":0,...},
{"ErrorCode":0,...},
{"ErrorCode":0,...},
]
in actual:
jsonResponse = [
{"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}},
{"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}}
]
then loop through:
var newArray = []
for(var i=0;i<jsonResponse.length;i++){ //loop through items
var stats = jsonResponse[i].SeriesSocialStats;
for(key in stats){ //loop through "SeriesSocialStats" numbers
newArray.push(stats[key]);
}
}
so it will be like:
newArray = [
{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"},
{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}
]
You could do
var obj1 = {"ErrorCode":0,"SeriesSocialStats":{"8970471":{"faves":1,"friendFaves":0,"friendLikes":0,"likes":1,"myFaves":1,"myLikes":0,"seriesId":"8970471"}}};
var obj2 = {"ErrorCode":0,"SeriesSocialStats":{"184072":{"faves":2,"friendFaves":0,"friendLikes":0,"likes":2,"myFaves":1,"myLikes":0,"seriesId":"184072"}}};
var arr = [];
arr.push(ob1.SeriesSocialStats);
arr.push(ob2.SeriesSocialStats);
Best way convert your server response to array structure, like mentioned by Joseph, instead of doing double processing from object to array.

Categories

Resources