Hos to get a json nested in laravel - arrays

I'm use laravel 7
I want a json like this:
"declaracion": {
"situacionPatrimonial": {
"datosGenerales": {
"nombre": "Pedro",
"primerApellido": "Perez",
"segundoApellido": "García",
"curp": "BADD110313HCMLNS09",
}
}
}
This branch works fine, I have no problem to generate it:
"datosGenerales": {
"nombre": "Pedro",
"primerApellido": "Perez",
"segundoApellido": "García",
"curp": "BADD110313HCMLNS09",
}
My code looks like this
$records = [];
foreach ($declaraciones as $declaracion) {
$record = [];
$record['datosGenerales']=$declaracion->datosGeneralesApi($id,$declaracion->servidor_publico);
$records[] = $record;
}
return $records;
datosGeneralesApi it's a trait
But i don´t know how add above o nest this branches
"declaracion": {
"situacionPatrimonial": {
Please any ideas? Thanks in advance

I may not quite understand your question, but I hope I can help
$records = [];
foreach ($declaraciones as $declaracion) {
// Here we create the nested items:
$record = [
"declaracion" => [
"situacionPatrimonial" => []
]
];
// Now access it
$record["declaracion"]["situacionPatrimonial"]['datosGenerales'] = $declaracion->datosGeneralesApi($id,$declaracion->servidor_publico);
$records[] = $record;
}
return $records;
You could also consider doing this a couple of other ways, without accessing with keys:
$record = [
"declaracion" => [
"situacionPatrimonial" => $declaracion->datosGeneralesApi($id,$declaracion->servidor_publico);
]
];
$records[] = $record;
Or create it in a much more structured way:
// Create the last element:
$situacionPatrimonial = $declaracion->datosGeneralesApi($id,$declaracion->servidor_publico);
// Wrap that in the next element:
$declaration = ["situacionPatrimonial" => $situacionPatrimonial];
// Now create your record, with the wrapped element:
$record = ["declaracion" => $declaration];
$records[] = $record;
I hope this explains what you don't understand about nesting even if it doesn't directly answer your question.

I would recommend using Eloquent API Resources. You can easily nest different resources in each other and structure them in any way you want.

Related

ANGULAR Components array key in result get value by id

this.crudService.get('user.php?mode=test')
.subscribe((data:any) => {
{ for (var key in data) { this[key] = data[key]; } };
}
);
This use to work on angular 7 now on angular 13 i get this error (look image)
In template i was using the values for example in json string was and array and i had users, in template was {{users}} , {{posts}} etc.. now the this[key] give error , please help me out its very important can't find solution
i'll show an example code, and then applied to your code:
Example
// creating global variables to receive the values
users: any = null;
posts: any = null;
// simulating the data you will receive
data: any[] = [
{users: ['user1', 'user2', 'user3']},
{posts: ['post1', 'post2', 'post3']}
];
getCrudService() {
// access each object of the array
this.data.forEach(obj => {
// getting keys name and doing something with it
Object.keys(obj).forEach(key => {
// accessing global variable and setting array value by key name
this[String(key)] = obj[String(key)]
})
})
}
Apllied to your code
this.crudService.get('user.php?mode=test').subscribe((data:any) => {
data.forEach(obj => {
Object.keys(obj).forEach(key => {
this[String(key)] = obj[String(key)]
});
});
});
I hope it helped you, if you need help, just reply me.

Iterating through a JSON array and returning a subset of elements

I'm new to JS and trying to figure out how to iterate through a json array and return only a subset of elements. Specifically I would like to know how to return only the 'first_name' and 'last_name' from the Mock data in the attached code snippet. It seems like it should be straightforward but I'm scratching my head.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
people.forEach(person => {
for (let key in person) {
console.log(`${key} => ${person[key]}`);
}
Use the element names
people.forEach(person => {
console.log(JSON.stringify(person) + "\n");
console.log(person["first_name"], person["last_name"], "\n");
});
Produces this output:
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"}
Talbert Kohnert
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"}
Ruthie McKleod
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
Lenore Foister
You can try Object destructuring assignment of ES6 to achieve the requirement.
Working Demo :
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}];
let res = people.map(({first_name, last_name}) => first_name + ' ' + last_name);
console.log(res);
There are numerous way of achieving this output. One of most frequently used method is using map() of es6.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
//by map method
people.map((person,index)=>{
console.log(`${person.first_name} ${person.last_name}`)
})
// by forEach
people.forEach(person => {
console.log(`${person.first_name} ${person.last_name}`)
}
you can achieve this by using the map function.
map lets you iterate over each item in the array and return a new value for each iteration while returning a new array, so for your case:
let people = [
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
]
const newArray = people.map((person) => {
return {
first_name: person.first_name,
last_name: person.last_name
}
})
console.log(newArray)
here you get a new array with just the properties you need.

How do I use async in node.js

I have created a code in node.js, which use mongoDB. Everything is working fine, but when I use nested loop, it break and don't return the proper values.
DB1.find({},function(error,fetchAllDB1) {
var mainArray = new Array();
for (var i in fetchAllDB1) {
if(fetchAllDB1[i].name) {
var array1 = new Array();
var array2 = new Array();
array1['name'] = fetchAllDB1[i].name;
array1['logo'] = fetchAllDB1[i].logo;
array1['desc'] = fetchAllDB1[i].desc;
DB2.find({is_featured:'1', brand_id: fetchAllDB1[i]._id}, function(error,fetchDB2) {
for (var p in fetchDB2) {
var pArr=[];
pArr['_id'] = fetchDB2[p]._id;
pArr['name'] = fetchDB2[p].name;
pArr['sku'] = fetchDB2[p].sku;
pArr['description'] = fetchDB2[p].description;
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
console.log(pArr);
console.log('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
array2[p]=pArr;
}
array1['pp']= array2;
});
mainArray[i]=array1;
}
}
console.log('######### LAST #########');
console.log(mainArray);
console.log('######### LAST #########');
});
In my console message its showing
console.log('######### LAST #########');
All Values
console.log('######### LAST #########');
After that
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
All Values;
console.log('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<');
I want to use async in my code, so that all data fetching occur as below:
mainarray =
[
[array1] = All Values
[array2] = [0]
[1]
]
mainarray =
[
[array1] = All Values
[array2] = [0]
[1]
]
Your code is very confusing and overly complicated.
What you should do is (psuedo code):
DB1.find(foo) // returns one result
.then(getFromDB2);
function getFromDB2 (res){
return DB2.find(res); // make a query here with mongo drivers `$in`
}
Mongodb : $in operator vs lot of single queries

Using 'chunks' together with 'with' on Laravel query builder

dunno if this is possible at all.. I'm trying to query a large set of data with relations like so:
Parent::with([
'child' => function($query) {
$query->('published', '=', true);
$query->with('child.of.child', 'some.other.child');
$query->chunk(400, function($childs) {
// how is it now possible to add the $childs to the parent result??
});
}
]);
$parent = [];
Parent::with(
[
'childs' => function ($query) use (&$parent) {
$query->where('STATUS', '!=', 'DELETED');
$query->with('some.child', 'some.other.child');
$parent['models'] = $query->getParent()
->getModels();
$query->chunk(
400, function ($result) use ($query, &parent) {
$query->match($parent['models'], $result, 'child-relations-name');
});
}
])
->get();
Now $parent['models'] contains the tree with all the nested child relations... Dunno if this is the smartest way to do so, but it works for now.

Convert Array of objects to Array in angularjs

I have this data inside my controller form:
$scope.reports = [
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
},
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
}
];
The above data is array of objects, I want them to convert in array. I used this code below to convert them in array:
var details=[];
for(var index in $scope.reports){
var tripcode = $scope.reports[index].tickettripcode;
var dateOfDepature = $scope.reports[index].departuredate.split('-');
details.push(tripcode, dateOfDepature[2]);
}
if(details[tripcode][dateOfDeparture[2]]){
details[tripcode][dateOfDeparture[2]] = details[tripcode][dateOfDeparture[2]] +1;
}
else {
details[tripcode][dateOfDeparture[2]] =1;
}
The code is not working fine with me and I do not know why. I have a doubt if I am doing array manipulation in a right way. I have error dateOfDeparture is not defined. I already defined the dateOfDeparture so why I getting this error. I just wanted to get the output which looks like this:
details = Array (
[3] =>Array
(
[10] =>2
)
)
The [3]is tickettripcode and [10] is the day of depaturdate. The 2 means number of departuredate in that date.
Any help would be much appreciated.
This is the link of my fiddle : https://jsfiddle.net/n1bw2u36/
Thanks in advance!
Unfortunately there are a lot of things you should learn about javascript.
By the way, I would expect that you will get what you want with the code like this.
var reports = [
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
},
{
departuredate:"2015-03-10",
routeline:"PASAY - CAGAYAN",
seatingtypescode:"ABS",
tickettripcode:"3",
tripcodetime:"16:30:00"
}
];
var table = {};
for (index=0; index<reports.length; index++){
var tripcode = reports[index].tickettripcode;
var dateOfDepature = reports[index].departuredate.split('-');
var date = dateOfDepature[2];
var map = table[tripcode];
if (map===undefined){
map = {};
table[tripcode] = map;
}
if (map[date]===undefined){
map[date] = 0;
}
map[date]++;
}
You can use "table" like this.
console.log(table);
console.log(table[3][10]);

Resources