how to group result with json key name in laravel - json

user table
id name age
1 TuTu 3
2 SuSu 4
3 YuYu 4
4 MoMo 4
I want to output json like this.
[
{
"age": 3,
"user": [
{
"id": 2,
"name": "TuTu"
}
]
},
{
"age": 4,
"user": [
{
"id": 2,
"name": "SuSu"
},
{
"id": 3,
"name": "YuYu"
},
{
"id": 4,
"name": "MoMo"
}
]
}
]
User::get()->groupBy("age") not working expected.
How could add json key age and user like above format in laravel?

The answer gives you the desired output, however consider using an API Resource for JSON Response.
$response = [];
User::get()->groupBy('age')->each(function ($item, $key) use (&$response) {
$temp = [];
$temp['age'] = $key;
$temp['user'] = $item->transform(function ($i, $k) {
unset($i['age']);
return $i;
})->all();
$response[] = $temp;
});
var_dump($response); // Your Output JSON

Related

How to display record count in laravel?

this is my controller query:
$orderStatistics = OrderHeader::orderBy('order_status')
->select(DB::raw('order_status,count(*) as count'))
->groupBy('order_status')
->get();
and this returns a response as this:
"data": [
{
"order_status": "APR",
"count": 2
},
{
"order_status": "CNCL",
"count": 4
},
{
"order_status": "NTE",
"count": 3
},
{
"order_status": "PND",
"count": 2
},
{
"order_status": "SHP",
"count": 1
}
]
how can I return the relevant order_status and it's count for example as this:
APR : 2
You can use transform function on your collection:
$result = $result->transform(function($re){
return //your changes on an object ($re)
})
If you want make an array for JsonResponse:
$data=[];
foreach($results as $re){
$data[$re->order_status]=$re->count;
}
return response()->json($data);
you can try this way to format data like APR : 2 this ..
$orderStatistics = OrderHeader::orderBy('order_status')
->select(DB::raw('order_status,count(*) as count'))
->groupBy('order_status')
->get();
$orderStatistics = $orderStatistics->map(function($item){
return [
$item->order_status => $item->count,
];
});
$numb = 0;
$newOrderStatus=[];
foreach($orderStatistics as $orderStatistic){
array_push($newOrderStatus, $orderStatistic->data[$numb]->order_status.':'.$orderStatistic->data[$numb]->count;
$numb++
}
echo $newOrderStatus[0];// your example but you just return $newOrderStatus
return response()->json($newOrderStatus);
This is what i would think of fast if you want to echo it to a view as array object you just parse return response()->json($newOrderStatus) But as you receive it javascript will see it as a string so you have to parseJson(receiveddata);

Es6: Create an array of objects from a json

I have a json in the below format.
[
{"id": 1,
"name": "peter" },
{"id": 2,
"name": "john" },
{"id": 3,
"name": "justin" }
.
.
{"id": 500,
"name": "david" },
]
I am trying to create an array in batches of 10 in the below format
[
{
{"id": 1,
"name": "peter" },
.
.
{"id": 10,
"name": "nixon" },
},
{
{"id": 11,
"name": "nancy" },
.
.
{"id": 20,
"name": "underwood" },
}
.
.
]
I tried using reduce and tried for loop to loop through it, but was unsuccessful
Here's a demo.
const str = "abcdefghigklmnopqrstuvwxyz";
let data = [];
for(let i = 0; i < 26; i++){
data.push({id : i, name: str.charAt(i)});
}
let res = data.reduce((acc, d) => {
let groupId = Math.floor(d.id / 10);
acc[groupId] = acc[groupId] || {};
acc[groupId][d.id] = d;
return acc;
}, {});
console.log(Object.values(res));
If you can ensure that id is the same sequence as their position in array, i think simply slice will better.

ES6 : How to push unique values in an Array while adding the duplicate ones?

I have an array of objects like :
[
{
"name": "Apple",
"amount": 5
},
{
"name": "Tomato",
"amount": 10
}
]
Requirement is when I push a object like
{
"name": "Apple",
"amount": 10
}
Expected Result:
[
{
"name": "Apple",
"amount": 15
},
{
"name": "Tomato",
"amount": 10
}
]
But on pushing unique entry like {"name":"Orange","amount":15}, the resulting array should be:
[{"name":"Apple","amount":5},{"name":"Tomato","amount":10},{"name":"Orange","amount":15}]
Pseudocode :
1) check if the entry exists.
2) get the index
3) if exist update the array of objects
3) if not exist Push the entry to the array of objects
const x = [{"name":"Apple","amount":5},{"name":"Tomato","amount":10}]
const toPush = {"name":"Apple","amount":30}
//(1 & 2) it would return a value greater than or equal to 0 if it exist
var indx= x.findIndex(q=>q.name == toPush.name)
// 3
if( getIndex >= 0 ) {
x[indx] = toPush
}
// 4
else {
x.push(toPush)
}

Using jq to compare two fields from same json and printing some other field as a result

I have json data in following format
{
"body": [
{
"username": "name1",
"id": "4444"
},
{
"username": "name2",
"id": "5555"
}
],
"meta": {
"input": "name1"
}}
Given this data I want to match the "username"s in the body with "meta.input" and if there is a match return/print related id.
jq solution:
jq '.meta.input as $meta | .body[] | select(.username == $meta).id' input.json
The output:
"4444"
.meta.input as $meta - assigning .meta.input key value to $meta variable for further comparison
This should be as simple as that:
var data = {
"body": [{
"username": "name1",
"id": "4444"
}, {
"username": "name2",
"id": "5555"
}],
"meta": {
"input": "name1"
}
};
function getID(data) {
var username = data.meta.input;
var userID;
for (i in data.body) {
if (data.body[i].username === username) {
userID = data.body[i].id;
break;
}
}
return userID;
}
var id = getID(data);
alert(id);

How to use captured value from URL to select JSON data in Django

Let's assume that I have GET request with URL domain/search/?value=123 and data in JSON:
[
{
"id": 1,
"value": 123,
"value2": 123123
},
{
"id": 2,
"value": 1,
"value2": 214
}
]
I would like to get data where value = 123. In this case:
[
{
"id": 1,
"value": 123,
"value2": 123123
}
]
I have found information how to capture parameters from URL in this post. I wonder what I should do now to find best solution in Django. Thanks in advance.
How can I use it in views.py:
if request.method == 'GET':
myObject = myObjectClass.objects.all()
serializer = myObjectSerializer(myObject, many=True)
return Response(serializer.data)
when data from JSON is not only an integer.
This is how to get it in python:
data = [
{
"id": 1,
"value": 123,
"value2": 123123
},
{
"id": 2,
"value": 1,
"value2": 214
}
]
result = None
for item in data:
if item['value'] == 123:
result = [item]
break
print(result)
Here is a javascript code to do this :-
function test()
{
//alert("Hi");
var text = '[{"id":1,"value":123,"value2":123123},{"id":2,"value":1,"value2":214}]'
json = JSON.parse(text);
var result = [];
for(var i = 0; i < json.length; i++) {
var obj = json[i];
if(obj['value'] == 123){
result.push(obj);
}
}
console.log(result);
}
In views.py , you can get the value of the URL through request object
data = [
{
"id": 1,
"value": 123,
"value2": 123123
},
{
"id": 2,
"value": 1,
"value2": 214
}
]
print [ item for item in data if item['value'] == request.GET.get('value') ]