How to Insert json object into sqlite in react native? - json

How to store json object in react native sqlite storage?
How to insert JSON OBJECT data into SQLite
Hello, I'm using react-native-sqlite-storage library, and i need to insert a json object into a table, and i have no idea how to approach the matter given that i have checked previous posts,
please help.

This is the answer to my own question, it was just a matter of using right import which was a hell to find(import SQLite from 'react-native-sqlite-2') , but thankfully i found it with the help of the following links:
Hopefully this would help someone else.
https://npmmirror.com/package/react-native-sqlite-2/v/1.0.0
https://github.com/appasaheb4/Tutorial_JsonData-into-insert-sqlitedb-ios-android-reactNative
enter code here
import React from 'react';
import SQLite from 'react-native-sqlite-2'
const Colors = [
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
{
color: "magenta",
value: "#f0f"
},
{
color: "yellow",
value: "#ff0"
},
{
color: "black",
value: "#000"
}
]
const App = () => {
const db = SQLite.openDatabase('test.db', '1.0', '', 1)
db.transaction(function(txn) {
txn.executeSql('DROP TABLE IF EXISTS Users', [])
txn.executeSql(
'CREATE TABLE IF NOT EXISTS Users(color_id INTEGER PRIMARY KEY NOT NULL, colors VARCHAR(30), Value VARCHAR(25))',
[]
)
for (var i = 0; i < Colors.length; i++) {
const array = Colors[i];
txn.executeSql('INSERT INTO Users (Value, colors) VALUES (?,?)',
[array.value,array.color])
txn.executeSql('SELECT * FROM `users`', [], function(tx, res) {
for (let i = 0; i < res.rows.length; ++i) {
console.log('item:', res.rows.item(i))
}
})
}
})
return(null)
}
export default App;

Related

Add Property to Object in loop with Lodash in Express

I need to add a "id" property converted in kebab-case to an object parsed from a JSON file:
App.js
app.get('/factions', (req, res) => {
const rawData = fs.readFileSync(__dirname + '/views/data/factions.json');
var factions = JSON.parse(rawData);
for (var key in factions) {
factions.key["id"] = _.kebabCase(key);
}
console.log(factions);
res.render('pages/factions', {
factionList: factions
});
});
This way doesn't work, if I try factions["Faction One"]["id"] = _.kebabCase(key); I can see "id" : "faction-one" is added to Faction One. But if I use the key value doesn't.
JSON
{
"Faction One": {
"color": "blue"
},
"Faction Two": {
"color": "red"
}
}
Solved with
for (var key in factions) {
factions[key].id = _.kebabCase(key);
}

Need to shift the child nodes in json to parent node

I have the following JSON -
[{
"ctin":"guju3j3jgjh3b",
"inv":[
{
"inum":"OS1920/16060",
"idt":"01-08-2019",
"val":17000.00,
"pos":"20",
"rchrg":"N"
}, {
"inum":"OS1920/16066",
"idt":"02-08-2019",
"val":17602.00,
"pos":"29",
"rchrg":"N"
}
]
},{
"ctin":"guj324djgjh3b",
"inv":[
{
"inum":"OS1920/16064",
"idt":"03-08-2019",
"val":19125.00,
"pos":"26",
"rchrg":"N"
}
]
}
.
.
.
]
I need to combine the child and the parent node.
So that the result will come as following -
[{
"ctin":"guju3j3jgjh3b",
"inum":"OS1920/16060",
"idt":"01-08-2019",
"val":17000.00,
"pos":"20",
"rchrg":"N"
}, {
"ctin":"guju3j3jgjh3b",
"inum":"OS1920/16066",
"idt":"02-08-2019",
"val":17602.00,
"pos":"29",
"rchrg":"N"
}, {
"ctin":"guj324djgjh3b",
"inum":"OS1920/16064",
"idt":"03-08-2019",
"val":19124,
"pos":"26",
"rchrg":"N"
},
.
.
.
]
Tried searching SO, but no luck.
Also, tried removing the "INV" node, but no luck. It just goes [object object] in Angular due to the looping of nodes inside one another.
It can be done using map function and concat:
const data = [{
"ctin":"guju3j3jgjh3b",
"inv":[
{
"inum":"OS1920/16060",
"idt":"01-08-2019",
"val":17000.00,
"pos":"20",
"rchrg":"N"
}, {
"inum":"OS1920/16066",
"idt":"02-08-2019",
"val":17602.00,
"pos":"29",
"rchrg":"N"
}
]
},{
"ctin":"guj324djgjh3b",
"inv":[
{
"inum":"OS1920/16064",
"idt":"03-08-2019",
"val":19125.00,
"pos":"26",
"rchrg":"N"
}
]
}
];
and code is:
let notFlattened = data.map(({ctin, inv}) => {
inv = inv.map(r=> {
r.ctin = ctin;
return r;
});
return inv;
})
let merged = [].concat.apply([], notFlattened);
console.log(merged);
I can only assume that the JSON is an array. You can use a combination of the .map, .reduce and .concat methods of Array to get what you want:
const result = data
.map((item) => item.inv.map((inv) => ({ ctin: item.ctin, ...inv })))
.reduce((a, b) => a.concat(b), []);
Try This,
for (var j = 0; j < this.datasource.length; j++) {
for (var i = 0; i < this.datasource1[j].inv.length; i++) {
this.datasource[j].inv[i].ctin = this.datasource[j]["ctin"];
}
/* delete this.datasource[j]['ctin'];
this.result.push(this.datasource[j].inv); */
}

Segregate and arrange data in specific format in Angular?

Hi I am developing Angular 5 application. I am trying to arrange data in specific format. I have json data. I want to convert it to specific format.
Below is the specific format.
this.nodes = [
{
name: 'root1',
children: [
{ name: 'child1' }
]
},
{
name: 'root2',
hasChildren: true
},
{
name: 'root3'
}
];
Below is my data.
{
"userid":"e75792f8-cfea-460e-aca2-07a778c92a7c",
"tenantid":"00000000-0000-0000-0000-000000000000",
"username":"karthik",
"emailaddress":"john#krsars.onmicrosoft.com",
"isallowed":false,
"userroles":[
{
"userroleid":"b81e63d1-09da-4aa0-af69-0f086ddb20b4",
"userid":"e75792f8-cfea-460e-aca2-07a778c92a7c",
"roleid":"85d2f668-f523-4b64-b177-b1a78db74234",
"tenantappid":1,
"validfrom":"2018-01-24T00:00:00",
"validto":"2018-01-24T00:00:00",
"isactive":true,
}
]
}
From the above data, I am trying to convert. From the above data each key/value pair I am converting it to format above given, For example, "userid":"e75792f8-cfea-460e-aca2-07a778c92a7c" I want to make it as
{
name: 'userid',
children: [
{ name: 'e75792f8-cfea-460e-aca2-07a778c92a7c' }
]
}
So below I is my code.
for (let key in results) {
if(results[key] instanceof Array){
this.nodes+=
name:key,
hasChildren: true
}+"}"
}
else
{
this.nodes+="{"+name=key,
children: [
{ name: results[key] }
]+"}"
}
}
Finally When i tried to display my data in console.
console.log(this.nodes);
Above my code does not work. Can someone help me to make this work? Any help would be appreciated. Thank you.
Here is a working example. Just to show you which way to go:
doIt() {
let results = JSON.parse('{"userid":"e75792f8-cfea-460e-aca2-07a778c92a7c","tenantid":"00000000-0000-0000-0000-000000000000","username":"karthik","emailaddress":"john#krsars.onmicrosoft.com","isallowed":false,"userroles":[{"userroleid":"b81e63d1-09da-4aa0-af69-0f086ddb20b4","userid":"e75792f8-cfea-460e-aca2-07a778c92a7c","roleid":"85d2f668-f523-4b64-b177-b1a78db74234","tenantappid":1,"validfrom":"2018-01-24T00:00:00","validto":"2018-01-24T00:00:00","isactive":true}]}');
const nodes = [];
for (const key in results) {
if (results[key] instanceof Array) {
const containerTyp2 = {name: '', hasChildren: false};
containerTyp2.name = key;
containerTyp2.hasChildren = true;
nodes.push(containerTyp2);
} else {
const object = {name: ''};
const containerTyp1 = {name: '', children: []};
object.name = key;
containerTyp1.name = key;
containerTyp1.children.push(object);
nodes.push(containerTyp1);
}
}
console.log('nodes: ', nodes);
}

Merging 2 REST endpoints to a single GraphQL response

New to graphQL, I'm Using the following schema:
type Item {
id: String,
valueA: Float,
valueB: Float
}
type Query {
items(ids: [String]!): [Item]
}
My API can return multiple items on a single request of each type (A & B) but not for both, i.e:
REST Request for typeA : api/a/items?id=[1,2]
Response:
[
{"id":1,"value":100},
{"id":2,"value":30}
]
REST Request for typeB : api/b/items?id=[1,2]
Response:
[
{"id":1,"value":50},
{"id":2,"value":20}
]
I would like to merge those 2 api endpoints into a single graphQL Response like so:
[
{
id: "1",
valueA: 100,
valueB: 50
},
{
id: "2",
valueA: 30,
valueB: 20
}
]
Q: How would one write a resolver that will run a single fetch for each type (getting multiple items response) making sure no unnecessary fetch is triggered when the query is lacking the type i.e:
{items(ids:["1","2"]) {
id
valueA
}}
The above example should only fetch api/a/items?id=[1,2] and the graphQL response should be:
[
{
id: "1",
valueA: 100
},
{
id: "2",
valueA: 30
}
]
So I assumed you are using JavaScript as the language. What you need in this case is not to use direct query, rather use fragments
So the query would become
{
items(ids:["1","2"]) {
...data
}}
fragment data on Item {
id
valueA
}
}
Next in the resolver we need to access these fragments to find the fields which are part of the fragment and then resolve the data based on the same. Below is a simple nodejs file with same
const util = require('util');
var { graphql, buildSchema } = require('graphql');
var schema = buildSchema(`
type Item {
id: String,
valueA: Float,
valueB: Float
}
type Query {
items(ids: [String]!): [Item]
}
`);
var root = { items: (source, args, root) => {
var fields = root.fragments.data.selectionSet.selections.map(f => f.name.value);
var ids = source["ids"];
var data = ids.map(id => {return {id: id}});
if (fields.indexOf("valueA") != -1)
{
// Query api/a/items?id=[ids]
//append to data;
console.log("calling API A")
data[0]["valueA"] = 0.12;
data[1]["valueA"] = 0.15;
}
if (fields.indexOf("valueB") != -1)
{
// Query api/b/items?id=[ids]
//append to data;
console.log("calling API B")
data[0]["valueB"] = 0.10;
data[1]["valueB"] = 0.11;
}
return data
},
};
graphql(schema, `{items(ids:["1","2"]) {
...data
}}
fragment data on Item {
id
valueA
}
`, root).then((response) => {
console.log(util.inspect(response, {showHidden: false, depth: null}));
});
If we run it, the output is
calling API A
{ data:
{ items: [ { id: '1', valueA: 0.12 }, { id: '2', valueA: 0.15 } ] } }
If we change the query to
{
items(ids:["1","2"]) {
...data
}}
fragment data on Item {
id
valueA
valueB
}
}
The output is
calling API A
calling API B
{ data:
{ items:
[ { id: '1', valueA: 0.12, valueB: 0.1 },
{ id: '2', valueA: 0.15, valueB: 0.11 } ] } }
So this demonstrates how you can avoid call for api A/B when their fields are not needed. Exactly as you had asked for

How to update an object within an array with immutable.js

I wish to update an objects in an array using immutable.js
My object looks like this:
{
location: '',
cars: [
{id: 1, color: blue},
{ id: 2, color: red}
]
};
In my code I get for example car id: 2 and change the color { id: 2, color: black}
I now wish to update the car which is at index 1 .
I tried :
const car = { id: 2, color: black}
updateIn([ 'cars' ], list => list.push(car));
This will only add a new car at the end.
Which function in Immutable JS can I use to update car id # 2.
What’s the correct way to do this with immutable.js
const car = { id: 2, color: black};
const indexToBeUpdated = 1;
updateIn(["cars", indexToBeUpdated], () => car);
whatever the index is, you need to pass it to updateIn methods first argument, which is an array.
Update element in immutable list by condition:
const data = fromJS({
location: '',
cars: [
{id: 1, color: blue},
{ id: 2, color: red}
]
});
const car = { id: 2, color: black}
const index = data.get(['cars']).findIndex(listItem => {
// condition here
return listItem.get('id') === car.id;
});
const new_data = data.setIn(['cars', index], car);