firebase automatic ID generation and insert value into array - arrays

I'm trying to insert data into my firebase JSon, which has the following structure
{
"gerechten" : [ {
"id" : "1",
"name" : "spaghetti",
"description" : "Spaghetti bolognese met veel liefde gemaakt op grootmoeders wijze.",
"kind" : "Pasta",
"preparation" : "1)Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",
"img" : "../../assets/img/gerechten/spaghetti.jpg",
"ingredients" : [ "5kg wortelen", "3 aardappelen", "1 komkommer", "2 eieren", "3 eetlepels bloem", "50g zout" ]
} ]
}
as you see, i got an array 'gerechten" and inside each array another array "ingredients". Right now i can add a items but i have no idea how to fill my "ingredients".
Is there a way to let the user give inputs and with each ',' there is a new ingredient? Eq;
5 eggs, 2 appels, 1 spoon of suger
sould create
"ingredients" : ["5 eggs", "2 appels", "1 spoon of suger"]
Also, as of now I have to insert my id manually, how can I make it so it takes automatic the next ID? when I leave the ID empty I got this result:
Firebase arror
Its does not put it inside an array
this is how i do it at the moment:
create.ts:
gerecht = {
description: "",
kind: "",
name: "",
prepartion: "",
ingredients: "",
id: "",
img: ""
}
create() {
this.db.create(this.gerecht.id, this.gerecht.description, this.gerecht.kind, this.gerecht.name, this.gerecht.prepartion, this.gerecht.img, this.gerecht.ingredients)
this.navCtrl.push(HomePage)
}
firedataservice:
create(id: string, description: string, kind: string, name: string, preparation: string, img: string, ingredients: string) {
this.db.object('gerechten/'+id).update({
id: id,
description: description,
kind: kind,
name: name,
preparation: preparation,
img: img,
ingredients: ingredients
})
}

Related

findIndex keeps on returning -1 from json

I'm passing a some context data from redux state (using hooks) to my current component.
I need to find only a specific value from redux state and put in the local, component's state.
I'm using findIndex for that.
Although, based on my console.log's it should find a match, it's still returning -1 constantly.
I've been browsing stackoverflow and googling for hours and tried every example + tried to manipulate it, but no luck.
The state (list) state from Redux,
[
{
userId: 2,
id: 11,
title: 'et ea vero quia laudantium autem',
body: 'delectus reiciendis molestiae occaecati non minima eveniet qui voluptatibus\naccusamus in eum beatae sit\nvel qui neque voluptates ut commodi qui incidunt\nut animi commodi'
},
{
userId: 2,
id: 12,
title: 'in quibusdam tempore odit est dolorem',
body: 'itaque id aut magnam\npraesentium quia et ea odit et ea voluptas et\nsapiente quia nihil amet occaecati quia id voluptatem\nincidunt ea est distinctio odio'
},
{
userId: 2,
id: 13,
title: 'dolorum ut in voluptas mollitia et saepe quo animi',
body: 'aut dicta possimus sint mollitia voluptas commodi quo doloremque\niste corrupti reiciendis voluptatem eius rerum\nsit cumque quod eligendi laborum minima\nperferendis recusandae assumenda consectetur porro architecto ipsum ipsam'
},
{
userId: 2,
id: 14,
title: 'voluptatem eligendi optio',
body: 'fuga et accusamus dolorum perferendis illo voluptas\nnon doloremque neque facere\nad qui dolorum molestiae beatae\nsed aut voluptas totam sit illum'
},
{
userId: 2,
id: 15,
title: 'eveniet quod temporibus',
body: 'reprehenderit quos placeat\nvelit minima officia dolores impedit repudiandae molestiae nam\nvoluptas recusandae quis delectus\nofficiis harum fugiat vitae'
},
{
userId: 2,
id: 16,
title: 'sint suscipit perspiciatis velit dolorum rerum ipsa laboriosam odio',
body: 'suscipit nam nisi quo aperiam aut\nasperiores eos fugit maiores voluptatibus quia\nvoluptatem quis ullam qui in alias quia est\nconsequatur magni mollitia accusamus ea nisi voluptate dicta'
},
{
userId: 2,
id: 17,
title: 'fugit voluptas sed molestias voluptatem provident',
body: 'eos voluptas et aut odit natus earum\naspernatur fuga molestiae ullam\ndeserunt ratione qui eos\nqui nihil ratione nemo velit ut aut id quo'
},
{
userId: 2,
id: 18,
title: 'voluptate et itaque vero tempora molestiae',
body: 'eveniet quo quis\nlaborum totam consequatur non dolor\nut et est repudiandae\nest voluptatem vel debitis et magnam'
},
{
userId: 2,
id: 19,
title: 'adipisci placeat illum aut reiciendis qui',
body: 'illum quis cupiditate provident sit magnam\nea sed aut omnis\nveniam maiores ullam consequatur atque\nadipisci quo iste expedita sit quos voluptas'
},
{
userId: 2,
id: 20,
title: 'doloribus ad provident suscipit at',
body: 'qui consequuntur ducimus possimus quisquam amet similique\nsuscipit porro ipsam amet\neos veritatis officiis exercitationem vel fugit aut necessitatibus totam\nomnis rerum consequatur expedita quidem cumque explicabo'
}
]
useEffect(() => {
if(list){
let allSectionsCopy = JSON.parse(JSON.stringify(list));
console.log(allSectionsCopy); // outputs the above array
let sectionIndex = allSectionsCopy.findIndex(
item => item.id === param.id
);
console.log(param.id) //returns 16 (because my react route is /dashboard/16 )
console.log(sectionIndex) // this returns -1
// let sectionToUpdate = allSectionsCopy[sectionIndex];
// setPage(sectionToUpdate)
}
}, [state]);
Index is returning -1 instead of 5
Any help would be appreciated.
Thanks in advance
Looks like param.id is a string and your index is an integer.

Angular 6 - Convert JSON to array

Hellog guys , i am trying to convert json data to object array for add these data to kendo grid but i am getting this error
Uncaught (in promise): TypeError: Cannot read property 'slice' of undefined
This error mean my data format isn't correct !.
This how data in json file are :
[
{
"orderNumber": 1,
"orderTable": "905503111-9",
"orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
"orderDate": "5/4/2018",
"orderPrice": 79
}
]
But i want them to be like this :
{
"data": [
{
"orderNumber": 1,
"orderTable": "905503111-9",
"orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
"orderDate": "5/4/2018",
"orderPrice": 79
}
],
}
Here an example of how i am accessing json file (orders.ts)
import { orders } from './orders';
import { employees } from '../employee/employees';
#Component({
selector: 'app-order',
templateUrl: './order.component.html',
styleUrls: ['./order.component.css']
})
export class OrderComponent implements OnInit {
public result;
public data = orders;
}
I tried many solutions like json.parse() and json.stringify() but didn't get what i need.
Note : I am using json file (orders.ts) that exist in my project.
var data = [
{
"orderNumber": 1,
"orderTable": "905503111-9",
"orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
"orderDate": "5/4/2018",
"orderPrice": 79
}
];
var newData = {
"orderNumber": 1,
"orderTable": "905503111-9",
"orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
"orderDate": "5/4/2018",
"orderPrice": 79
};
data.push(newData)
console.log(newData);
you can do it simply like this and make sure name is same as data
data=[
{
"orderNumber": 1,
"orderTable": "905503111-9",
"orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
"orderDate": "5/4/2018",
"orderPrice": 79
}
];
let d={data}
console.log(d)
or
let d={}
d.data=[
{
"orderNumber": 1,
"orderTable": "905503111-9",
"orderDescription": "Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.",
"orderDate": "5/4/2018",
"orderPrice": 79
}
]
console.log(d)
you will get the desired output

How to join two table hash in ruby

I'm training ruby and I need to do an exercice but I don't know how to get data
I have this
DB = [
{
title: "My first article",
content: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id ratione harum illo, dicta minima rerum quod natus cupiditate voluptatibus rem! Amet reprehenderit voluptatum animi, eligendi quia quos reiciendis veritatis magni.",
photo: "https://google.fr",
rating: "2"
},
{
title: "An second article",
content: "Eventually the guys with real ideas not running a scam on the world will overcome. I used an exclamation just to be an asshole and also to make a point! LOL Young Thug is super inspiring to me. Amazing artist!!! I also wanted to point out that it’s the first album to go number 1 off of streaming!!! ",
photo: "https://google.fr",
rating: "2"
},
{
title: "3 article",
content: "also to Kim’s hair and makeup Lorraine jewelry and the whole style squad at Balmain and the Yeezy team. When companies doubt me they doubt us. Wes daytime",
rating: "4"
},
]
COMMENTS = [
["Hello1"],
["comment2"],
["comment3"],
]
and I would like this
DATAS = [ {
title: "My first article",
content: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id ratione harum illo, dicta minima rerum quod natus cupiditate voluptatibus rem! Amet reprehenderit voluptatum animi, eligendi quia quos reiciendis veritatis magni.",
photo: "https://google.fr",
rating: "2"
}, ["Hello1"],
....
]
If you can me it's will be very hepful because table for me it's quite hard, Thank you
You didn't write any code, so I won't give you a complete answer.
You could get the desired result with Array#zip and Array#flatten.
flatten accepts an optional parameter for the number of nested arrays it should flatten.
So DB.zip(COMMENTS).flatten will be almost exactly what you want. You just need to provide the suitable parameter to flatten.

When I console.log(portfoliosArray) it returns an array or four arrays?

Instead of returning an array of objects, pulling from a JSON file, it returns an array of 4 arrays containing 4 objects? Why? JSON file name is portfolios.json.
'use strict';
var portfolioArray = [];
function Portfolio (portfoliosDataObj) {
this.title = portfoliosDataObj.title;
this.body = portfoliosDataObj.body;
this.img = portfoliosDataObj.img;
}
Portfolio.prototype.toHtml = function() {
var renderPortfolios = Handlebars.compile($('#portfolio-template').text());
return renderPortfolios(this);
console.log(this);
};
$.getJSON('/data/portfolios.json', function(portfolios) {
portfolios.forEach(function(portfoliosDataObject) {
var portfolio = new Portfolio(portfoliosDataObject);
portfolioArray.push(portfolios);
console.log(portfolios);
});
});
function print () {
portfolioArray.forEach(function(data) {
$('#portfolioSection').append(data.toHtml());
});
}
Portfolio();
print();
JSON FILE - Adding for reference.
[{
"title": "CodeFellows/Code201",
"body": "content1",
"img": ""
},
{
"title": "CodeFellows/Code301",
"body": "lorem ipsum"
},
{
"title": "Upcoming Projects/Other interest",
"body": "lorem impsum",
"img": "/images/blog.jpg"
},
{
"title": "Illustrations",
"body": "lorem ipsum",
"img": "/images/portfolio.png"
}]
IGNORE need more content that isn't code to post....
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam porttitor leo at tellus facilisis, id suscipit ipsum suscipit. Aenean venenatis, quam semper efficitur hendrerit, odio diam condimentum odio, id sagittis lorem tellus vel mauris. Cras enim neque, malesuada sit amet lacinia et, ullamcorper non sapien. Integer id hendrerit nulla, vitae tristique tortor. Aenean in arcu eget massa pulvinar dictum. Aliquam dictum fermentum sapien id iaculis. Ut malesuada varius lacinia. Maecenas scelerisque facilisis mattis.
The file returns an array of 4 objects, and not arrays.
{
"title": "CodeFellows/Code201",
"body": "content1",
"img": ""
}
is a javascript object, not an array (notice the curly braces {}).
The outer one is an array. (notice the square brackets[]).
You can get to the objects by doing a console.log(portfolios[0]);
The issue is with this code. You are pushing portfolios in portfolioArray instead of portfolio. Also you were doing console.log for portfolios which is why it was showing 4 arrays. I have fixed the code. Let me know if it works for you.
$.getJSON('/data/portfolios.json', function(portfolios) {
portfolios.forEach(function(portfoliosDataObject) {
var portfolio = new Portfolio(portfoliosDataObject);
portfolioArray.push(portfolio);
console.log(portfolio);
});
});

Append JSON element to array using postgres 9.4

I am attempting to append a JSON element to an already existing array in my database. I know about jsonb_set however I can't upgrade to Postgres 9.4 as this is a groovy project and the latest postgresql version on Maven is 9.4.
I currently have a json structure like this:
"playersContainer": {
"players": [
{
"id": "1",
"name": "Nick Pocock",
"teamName": "Shire Soldiers",
"bio" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla imperdiet lorem tellus, in bibendum sem dignissim sed. Etiam eu elit sit amet lacus accumsan blandit sed ut dolor. Mauris vel dui non nisi vestibulum commodo vel id magna. Donec egestas magna in tincidunt mollis. Fusce mauris arcu, rhoncus ut lacus sed, fermentum ultrices elit. In sollicitudin at ex dapibus vestibulum. Pellentesque congue, est id lobortis viverra, mauris lectus pharetra orci, ut suscipit nisl purus vehicula est. Aliquam suscipit non velit vel feugiat. Quisque nec dictum augue.",
"ratings": [
1,
5,
6,
9
],
"assists": 17,
"manOfTheMatches": 20,
"cleanSheets": 1,
"data": [
3,
2,
3,
5,
6
],
"totalGoals": 19
}
}
I want to append new players to the player array and update my database, I tried doing an update but it wiped the rest of the data. Is there a way to target the players array and append the new json object to it?
Unfortunately 9.4 does not have json_set function. You can use something like this:
WITH old_players AS (
SELECT $1 AS j
), new_player AS (
SELECT $2 AS j
), all_players AS (
SELECT json_array_elements(j->'playersContainer'->'players') AS p
FROM old_players
UNION ALL
SELECT *
FROM new_player
) SELECT ('{"playersContainer": {"players": ' || json_agg(p) || '}}')::json
FROM all_players
;
You can use it as function:
CREATE OR REPLACE FUNCTION add_player(old_player json, new_player json) RETURNS json AS $$
WITH all_players AS (
SELECT json_array_elements(($1)->'playersContainer'->'players') AS p
UNION ALL
SELECT $2
)
SELECT ('{"playersContainer": {"players": ' || json_agg(p) || '}}')::json
FROM all_players
$$ LANGUAGE sql IMMUTABLE;
And after that you can just call it :
UPDATE site_content SET content = add_player(content, '{"id": "2", "name": "Someone Else"}') where id = :id;

Resources